<?php

namespace app\admin\controller;

use app\model\Videos;
use think\facade\Log;
use app\admin\service\TaskService;
use think\facade\Db;
use app\common\Common;
use think\facade\Cache;
use think\facade\Request;
use app\model\DailyDeliveryData;
use app\model\DeliveryData;
use app\model\Link;
use app\model\VideoDetails;
use app\model\DistributorsSharingStatistics;
use app\model\PayRecord;

/**
 * 定时任务
 */
class Task
{
    private $service;

    public function __construct(TaskService $service)
    {
        $this->service = $service;
    }

    // 剧集今日观看人数清零
    public function zeroNumberOfViewersToday()
    {
        Db::name('video_details')->where('today_number', '<>', 0)->update(['today_number' => 0]);
    }

    // 统计每个版权输入合作方每天的消费金额 每天晚上1点后执行
    public function partnersMonetaryStatistics()
    {
        $this->service->monetaryStatistics();
    }

    /**
     * 会员过期更新会员状态
     */
    public function checkMembers()
    {
        $data = Db::name('user')->where('is_members', 1)
            ->where('expiration_time', '<=', time())
            ->select()
            ->toArray();

        $ids = array_column($data, 'id');
        Db::name('user')->whereIn('id', $ids)->update(['is_members' => 0, 'expiration_time' => 0]);
    }

    // 更新剧集公众号提醒(观看提醒) 每天10:30提醒
    public function updateDramaRemind()
    {
        $startTime = strtotime(date('Y-m-d', time() - 86400) . ' 10:30:00');
        // $startTime = strtotime(date('Y-m-d', time()-2086400).' 10:00:00');
        $endTime = strtotime(date('Y-m-d') . ' 10:30:00');
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<', $endTime]
        ];

        // 获取昨天10点到今天10点短剧更新集数数据
        $data = Db::name('video_details')->where($where)->field('video_id, sort')->order('sort desc')->select()->toArray();

        $result = $videoIds = [];
        foreach ($data as $value) {
            if (!empty($result[$value['video_id']])) {
                if ($result[$value['video_id']] < $value['sort']) {
                    $result[$value['video_id']] = $value['sort'];
                }
            } else {
                $result[$value['video_id']] = $value['sort'];
            }

            if (!in_array($value['video_id'], $videoIds)) {
                $videoIds[] = $value['video_id'];
            }
        }

        // 获取短剧名称数据
        $videoData = Db::name('videos')->where(['id' => $videoIds])->field('id, name')->select()->toArray();
        $videoResult = array_column($videoData, 'name', 'id');

        // 获取用户订阅消息提醒数据
        $subscribeRecordData = Db::name('subscribe_record')->where(['video_id' => $videoIds])->field('uid, video_id, open_id, official_account_id')->select()->toArray();

        $officialAccountIds = array_column($subscribeRecordData, 'official_account_id');

        // 获取公众号数据
        $officialAccountData = Db::name('official_accounts')->where(['id' => $officialAccountIds])->field('id, original_id, watch_reminder, app_id, app_secret, applet_id')->select()->toArray();

        $appletIds = array_column($officialAccountData, 'applet_id');

        // 获取小程序数据
        $appletData = Db::name('applet')->where(['id' => $appletIds])->field('id, app_id')->select()->toArray();
        $appletResult = array_column($appletData, 'app_id', 'id');

        foreach ($officialAccountData as $key => $value) {
            $officialAccountData[$key]['applet_app_id'] = empty($appletResult[$value['applet_id']]) ? '' : $appletResult[$value['applet_id']];
        }

        $officialAccountResult = array_column($officialAccountData, null, 'id');

        // redis
        $redis = Cache::store('redis')->handler();
        $redisKey = config('redis_key.get_wechat_official_account_access_token');

        foreach ($subscribeRecordData as $key => $item) {
            if (!empty($officialAccountResult[$item['official_account_id']]) && $officialAccountResult[$item['official_account_id']]['watch_reminder'] == 1) {

                $accessToken = $redis->get($redisKey . $item['official_account_id']);

                if (empty($accessToken)) {
                    // 获取微信accessToken
                    $accessToken = Common::getWechatOfficialAccountAccessToken($officialAccountResult[$item['official_account_id']]['app_id'], $officialAccountResult[$item['official_account_id']]['app_secret'], $item['official_account_id']);
                }

                $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $accessToken;

                $videoName = $videoResult[$item['video_id']];

                $sort = $result[$item['video_id']];

                $appletAppId = $officialAccountResult[$item['official_account_id']]['applet_app_id'];

                $jumpUrl = config('enum.watch_video_link_jump_url') . '&video_id=' . $item['video_id'] . '&official_account_id=' . $item['official_account_id'] . '&uid=' . $item['uid'];

                $content = "亲，您上次看过的《" . $videoName . "》已更新到第" . $sort . "集，点击继续观看即可观看后续剧集~

<a data-miniprogram-appid='" . $appletAppId . "' data-miniprogram-path='" . $jumpUrl . "'>【继续观看】</a>

为方便下次阅读，请<a href='https://m.bsxiaoshuo.com/ding.html?u=1169925'>置顶公众号</a>";

                $text = '{
                    "touser":"' . $item['open_id'] . '",
                    "msgtype":"text",
                    "text":
                    {
                        "content":"' . $content . '"
                    }
                }';

                $wechatResult = Common::curlRequest($url, 'POST', $text);
                // dump($wechatResult);die;
            }
        }
    }

    // 未签到签到提醒 每天晚上8点提醒
    public function noSignRemind()
    {
        // 获取公众号数据
        $officialAccountData = Db::name('official_accounts')->where(['sign_reminder' => 1])->field('id, original_id, app_id, app_secret, applet_id')->select()->toArray();

        $officialAccountIds = array_column($officialAccountData, 'id');

        $officialAccountResult = array_column($officialAccountData, null, 'id');

        $where = [
            ['sign_time', '<', strtotime(date('Y-m-d'))],
            ['official_account_id', 'in', $officialAccountIds]
        ];

        $userData = Db::name('user')->where($where)->field('id, official_account_open_id, official_account_id, applet_id')->select()->toArray();

        foreach ($userData as $key => $value) {
            // code...
        }

        $redis = Cache::store('redis')->handler();
        $redisKey = config('redis_key.get_wechat_official_account_access_token');

        foreach ($userData as $key => $item) {

            if ($item['official_account_open_id']) {

                $accessToken = $redis->get($redisKey . $item['official_account_id']);

                if (empty($accessToken)) {
                    // 获取微信accessToken
                    $accessToken = Common::getWechatOfficialAccountAccessToken($officialAccountResult[$item['official_account_id']]['app_id'], $officialAccountResult[$item['official_account_id']]['app_secret'], $item['official_account_id']);
                }

                $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $accessToken;

                $appletAppId = Db::name('applet')->where(['id' => $item['applet_id']])->value('app_id');

                $jumpUrl = config('enum.sign_link_jump_url') . '?official_account_id=' . $item['official_account_id'] . '&uid=' . $item['id'];

                $content = "亲，您今天还没有签到哦，点击签到即可领取K币~

<a data-miniprogram-appid='" . $appletAppId . "' data-miniprogram-path='" . $jumpUrl . "'>点击签到</a>

为方便下次阅读，请<a href='https://m.bsxiaoshuo.com/ding.html?u=1169925'>置顶公众号</a>";

                $text = '{
                    "touser":"' . $item['official_account_open_id'] . '",
                    "msgtype":"text",
                    "text":
                    {
                        "content":"' . $content . '"
                    }
                }';

                $wechatResult = Common::curlRequest($url, 'POST', $text);
                // dump($wechatResult);die;
            }
        }
    }

    // 统计抖音每天投放数据
    public function dailyDeliveryData()
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);

        // 分销商链接不查询

        $distributorResponsibilityPersonIds = [];

        $distributorResponsibilityPerson = Db::name('responsibility_person')->where(['pid' => Db::raw('IS NOT NULL')])->field(['id', 'pid'])->select()->toArray();

        $distributorResponsibilityPersonPids = array_unique(array_column($distributorResponsibilityPerson, 'pid'));

        $notBranchOfficeManageData = Db::name('responsibility_person')->where([['id', 'in', $distributorResponsibilityPersonPids], ['is_branch_office_manage', '=', 0]])->field(['id'])->select()->toArray();

        $notBranchOfficeManageIds = array_column($notBranchOfficeManageData, 'id');

        foreach ($distributorResponsibilityPerson as $distributorResponsibility) {
            if (in_array($distributorResponsibility['pid'], $notBranchOfficeManageIds)) {
                $distributorResponsibilityPersonIds[] = $distributorResponsibility['id'];
            }
        }

        $linkData = Db::name('link')->where([['media_id', '=', 1], ['link_switch', '=', 1], ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds]])->field('id, video_id, video_detail_id, advertiser_id, version, project_id, rebate, subject_id, link_type')->select()->toArray();

        if (!empty($distributorResponsibilityPersonIds)) {
            // 获取统计当天关闭投放的链接数据
            $sql = 'select id, video_id, video_detail_id, advertiser_id, version, project_id, rebate, subject_id,link_type from ly_link where media_id=1 and from_unixtime(release_end_time, "%Y%m%d") = ' . date('Ymd', time() - 86400) . ' and responsibility_person_id not in (' . implode(',', $distributorResponsibilityPersonIds) . ')';

            $linkData1 = Db::query($sql);

            $linkAdvertiserIds = array_column($linkData, 'advertiser_id');
            $newlinkData = [];
            foreach ($linkData1 as $key => $value) {
                if (!in_array($value['advertiser_id'], $linkAdvertiserIds)) {
                    $newlinkData[] = $value;
                }
            }
            $linkData = array_merge($linkData, $newlinkData);
        }
        // 获取redis花费数据
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        // 
        $redisCostData = [];
        $redisCostData1 = $redis->get('oceanengine_business_finances_faily_data_yesterday:18006505024'); // 杭州泉起抖小
        $redisCostData2 = $redis->get('oceanengine_business_finances_faily_data_yesterday:sybyn6'); // 杭州泉起
        $redisCostData3 = $redis->get('oceanengine_business_finances_faily_data_yesterday:sybyn1'); // 泉起-抖小-艺达

        $redisCostDataLiuYi = json_decode($redisCostData1, true);
        $redisCostDataGuangZhou = json_decode($redisCostData2, true);
        $redisCostDataThree = json_decode($redisCostData3, true);

        if (!empty($redisCostDataLiuYi['data'])) {
            $redisCostData = $redisCostData + $redisCostDataLiuYi['data'];
        }
        if (!empty($redisCostDataGuangZhou['data'])) {
            $redisCostData = $redisCostData + $redisCostDataGuangZhou['data'];
        }
        if (!empty($redisCostDataThree['data'])) {
            $redisCostData = $redisCostData + $redisCostDataThree['data'];
        }

        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }
            // 花费
            $value['cost'] = !empty($redisCostData[$value['advertiser_id']]['non_grant_cost']) || !empty($redisCostData[$value['advertiser_id']]['return_goods_wallet_cost']) ? $redisCostData[$value['advertiser_id']]['non_grant_cost'] + $redisCostData[$value['advertiser_id']]['return_goods_wallet_cost'] : 0;
            // 所有花费
            $value['all_cost'] = !empty($redisCostData[$value['advertiser_id']]['cost']) ? $redisCostData[$value['advertiser_id']]['cost'] : 0;
            // 账户非赠款消耗(元)
            $value['non_grant_cost'] = !empty($redisCostData[$value['advertiser_id']]['non_grant_cost']) ? $redisCostData[$value['advertiser_id']]['non_grant_cost'] : 0;
            // 账户赠款消耗(元)
            $value['grant_cost'] = !empty($redisCostData[$value['advertiser_id']]['grant_cost']) ? $redisCostData[$value['advertiser_id']]['grant_cost'] : 0;
            // 共享赠款消耗(元)
            $value['return_goods_wallet_cost'] = !empty($redisCostData[$value['advertiser_id']]['return_goods_wallet_cost']) ? $redisCostData[$value['advertiser_id']]['return_goods_wallet_cost'] : 0;
            // 账户总余额(元)
            $value['balance'] = !empty($redisCostData[$value['advertiser_id']]['balance']) ? $redisCostData[$value['advertiser_id']]['balance'] : 0;
            // 账户非赠款余额(元)
            $value['non_grant_balance'] = !empty($redisCostData[$value['advertiser_id']]['non_grant_balance']) ? $redisCostData[$value['advertiser_id']]['non_grant_balance'] : 0;
            // 账户赠款余额(元)
            $value['grant_balance'] = !empty($redisCostData[$value['advertiser_id']]['grant_balance']) ? $redisCostData[$value['advertiser_id']]['grant_balance'] : 0;
            $data[] = $value;
        }

        if ($data) {
            $ids = array_column($data, 'id');

            // $linkData2 = [];
            // foreach ($linkData1 as $item) {
            //     if (!in_array($item['id'], $ids)) {
            //         $linkData2[] = [
            //             'id' => $item['id'],
            //             'video_id' => $item['video_id'],
            //             'video_detail_id' => $item['video_detail_id'],
            //             'advertiser_id' => $item['advertiser_id'],
            //             'version' => $item['version'],
            //             'project_id' => $item['project_id'],
            //             'rebate' => $item['rebate'],
            //             'cost' => 0,
            //             'link_type' => $item['link_type']
            //         ];
            //     }
            // }
            // $data = array_merge($data, $linkData2);
            // $ids = array_column($data, 'id');

            $timeStamp = time() - 86400;
            $start = date('Y-m-d', $timeStamp) . ' 00:00:00';
            $end = date('Y-m-d', $timeStamp) . ' 23:59:59';
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [$start, $end]]
            ];
            $userInfo = Db::name('user')->where($userWhere)->field('id, link_id')->select()->toArray();
            $payData = Db::name('pay_record')->where(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd', time() - 86400)])->field('link_id, uid, total_fee, activation_time, pay_merchant')->select()->toArray();

            $activationUids = $newUids = $newUserPayData = $rechargeNumber = $payResult = $activationUserNumData = $registerUserNumData = [];

            if ($userInfo) {
                $activationUids = array_column($userInfo, 'id');

                foreach ($userInfo as $value) {
                    $activationUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            // 注册用户数
            $registerUserData = Db::name('user')->where(['register_date' => date('Ymd', $timeStamp), 'link_id' => $ids])->field('id, link_id')->select()->toArray();
            if ($registerUserData) {
                $newUids = array_column($registerUserData, 'id');
                foreach ($registerUserData as $key => $value) {
                    $registerUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            $newUserNum = $tencentPayData = [];
            // 当天新用户充值（当期充值）
            $endTime = strtotime(date('Y-m-d'));
            $startTime = $endTime - 86400;

            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }

                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            $saveData = [
                'platform' => 1,
                'date' => date('Ymd', time() - 86400),
                'month' => date('Ym', time() - 86400),
                'total_cost' => 0,
                'activation_user_num' => count($activationUids),
                'current_recharge' => 0,
                'current_recovery' => 0,
                'total_recharge' => 0,
                'total_recovery' => 0,
                'fans_cost' => 0,
                'revenue' => 0,
                'per_capita_contribution' => 0,
                'created_at' => time(),
                'register_user_num' => count($newUids),
                'actual_cost' => 0,
                'recharge_user_num' => 0,
                'conversion_rate' => '0%',
                'virtual_payment' => 0,
                'all_cost' => 0,
                'non_grant_cost' => 0,
                'grant_cost' => 0,
                'return_goods_wallet_cost' => 0,
                'balance' => 0,
                'non_grant_balance' => 0,
                'grant_balance' => 0
            ];

            $totalClickNum = 0; // 所有链接总点击数
            $totalNewUserNumber = 0; // 所有链接新充人数

            $todayLanuchData = [];
            foreach ($data as $key => $item) {
                $data[$key]['platform'] = 1;
                $data[$key]['link_id'] = $item['id'];
                $data[$key]['date'] = date('Ymd', time() - 86400);
                $data[$key]['month'] = date('Ym', time() - 86400);

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                if (empty($currentRecharge) && (empty($item['cost']) || $item['cost'] == '0.00')) {
                    continue;
                }
                // 腾讯虚拟支付
                $virtualPayment = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $saveData['virtual_payment'] += $virtualPayment;
                $data[$key]['virtual_payment'] = $virtualPayment;

                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                $saveData['total_cost'] = $saveData['total_cost'] + $item['cost']; // 总花费
                $saveData['current_recharge'] = $saveData['current_recharge'] + $currentRecharge; // 当天所有链接当期充值

                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $rechargeSum = empty($rechargeNumber[$item['id']]) ? 0 : count($rechargeNumber[$item['id']]); // 充值笔数
                $data[$key]['conversion_number'] = $conversionNumber;
                $data[$key]['recharge_number'] = $rechargeSum;
                $data[$key]['conversion_cost'] = $conversionNumber == 0 ? 0 : round($item['cost'] / $conversionNumber, 2); // 转化成本
                $saveData['recharge_user_num'] = $saveData['recharge_user_num'] + $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $totalNewUserNumber = $totalNewUserNumber + $newUserNumber;

                // 激活用户数
                $activationUserNum = !empty($activationUserNumData[$item['id']]) ? count($activationUserNumData[$item['id']]) : 0;
                $data[$key]['activation_user_num'] = $activationUserNum;

                // 转化率
                $data[$key]['conversion_rate'] = empty($activationUserNum) ? '0%' : round($newUserNumber / $activationUserNum * 100, 2) . '%';
                $totalClickNum = $totalClickNum + $activationUserNum;

                $data[$key]['register_user_num'] = !empty($registerUserNumData[$item['id']]) ? count($registerUserNumData[$item['id']]) : 0; // 该链接当日注册用户

                $data[$key]['total_recharge'] = round($currentRecharge, 2);
                $saveData['total_recharge'] = $saveData['total_recharge'] + $currentRecharge; // 总充值

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献
                $data[$key]['created_at'] = time();

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } elseif (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                $data[$key]['actual_cost'] = $actualCost;
                $saveData['actual_cost'] = $saveData['actual_cost'] + $actualCost;
                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况 = 累计充值 - 实际花费
                $data[$key]['current_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 当期回收

                $data[$key]['fans_cost'] = !empty($activationUserNum) ? round($actualCost / $activationUserNum, 2) : 0; // 粉丝成本
                $saveData['all_cost'] += !empty($item['all_cost']) ? 0 : $item['all_cost'];
                $saveData['non_grant_cost'] += $item['non_grant_cost'];
                $saveData['grant_cost'] += $item['grant_cost'];
                $saveData['return_goods_wallet_cost'] += $item['return_goods_wallet_cost'];
                $saveData['balance'] += $item['balance'];
                $saveData['non_grant_balance'] += $item['non_grant_balance'];
                $saveData['grant_balance'] += $item['grant_balance'];

                unset($data[$key]['id']);
                unset($data[$key]['video_id']);
                unset($data[$key]['video_detail_id']);
                unset($data[$key]['version']);
                unset($data[$key]['project_id']);
                unset($data[$key]['rebate']);
                unset($data[$key]['subject_id']);

                $todayLanuchData[] = $data[$key];
            }
        }

        // 统计在投所有链接每天的投放数据
        $saveData['current_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['current_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 当期回收
        $saveData['total_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['total_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 累计回收
        $saveData['fans_cost'] = !empty($saveData['activation_user_num']) ? round($saveData['actual_cost'] / $saveData['activation_user_num'], 2) : 0; // 粉丝成本
        $saveData['revenue'] = round($saveData['total_recharge'] - $saveData['actual_cost'], 2); // 营收情况
        $saveData['per_capita_contribution'] = !empty($saveData['register_user_num']) ? round($saveData['current_recharge'] / $saveData['register_user_num'], 2) : 0; // 人均贡献
        $saveData['total_cost'] = round($saveData['total_cost'], 2);
        $saveData['all_cost'] = round($saveData['all_cost'], 2);
        $saveData['current_recharge'] = round($saveData['current_recharge'], 2);
        $saveData['total_recharge'] = round($saveData['total_recharge'], 2);
        $saveData['conversion_rate'] = !empty($totalClickNum) ? round($totalNewUserNumber / $totalClickNum * 100, 2) . '%' : '0%';

        Db::name('delivery_data')->insert($saveData);

        // 统计在投每条链接每天的投放数据
        $bool = Db::name('daily_delivery_data')->insertAll($todayLanuchData);
        return $bool;
    }

    // 统计快手每天投放数据
    public function kwaiDailyDeliveryData()
    {
        $linkData = Db::name('link')->where(['link_switch' => 1, 'media_id' => 2])->field('id, video_id, video_detail_id, advertiser_id, rebate')->select()->toArray();

        // 获取统计当天关闭投放的链接数据
        $sql = 'select id, video_id, video_detail_id, advertiser_id, version, project_id, rebate from ly_link where media_id=2 and from_unixtime(release_end_time, "%Y%m%d") = ' . date('Ymd', time() - 86400);
        $linkData1 = Db::query($sql);

        $linkAdvertiserIds = array_column($linkData, 'advertiser_id');
        $newlinkData = [];
        foreach ($linkData1 as $key => $value) {
            if (!in_array($value['advertiser_id'], $linkAdvertiserIds)) {
                $newlinkData[] = $value;
            }
        }
        $linkData = array_merge($linkData, $newlinkData);

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $appId = config('kwai.magnetic_force.app_id');
        $secret = config('kwai.magnetic_force.secret');
        $accessToken = Common::getKwaiAccessToken($appId, $secret);

        $hearder['headers'] = ['Access-Token:' . $accessToken];
        $hearder['json'] = 1;

        $startDate = date('Y-m-d', time() - 86400);
        $endDate = date('Y-m-d', time() - 86400);
        $data = $accountIds = [];
        $url = 'https://ad.e.kuaishou.com/rest/openapi/v1/advertiser/fund/daily_flows';

        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }
            $requestData = [
                'advertiser_id' => intval($value['advertiser_id']),
                'start_date' => $startDate,
                'end_date' => $endDate,
            ];

            $result = Common::_curl($url, $requestData, 'POST', $hearder);
            $result = json_decode($result, true);

            if (!$result['code']) {
                foreach ($result['data']['details'] as $item) {
                    $value['cost'] = $item['daily_charge']; // 今日花费
                    $data[] = $value;
                }
            } else {
                return ['message' => $result['message']];
            }

            $accountIds[] = $value['advertiser_id'];
        }

        if ($data) {
            $ids = array_column($data, 'id');

            $linkData2 = [];
            foreach ($linkData1 as $item) {
                if (!in_array($item['id'], $ids)) {
                    $linkData2[] = [
                        'id' => $item['id'],
                        'video_id' => $item['video_id'],
                        'video_detail_id' => $item['video_detail_id'],
                        'advertiser_id' => $item['advertiser_id'],
                        'version' => $item['version'],
                        'project_id' => $item['project_id'],
                        'rebate' => $item['rebate'],
                        'cost' => 0
                    ];
                }
            }
            $data = array_merge($data, $linkData2);
            $ids = array_column($data, 'id');

            $timeStamp = time() - 86400;
            $start = date('Y-m-d', $timeStamp) . ' 00:00:00';
            $end = date('Y-m-d', $timeStamp) . ' 23:59:59';
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [$start, $end]]
            ];
            $userInfo = Db::name('user')->where($userWhere)->field('id, link_id')->select()->toArray();
            $payData = Db::name('pay_record')->where(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd', time() - 86400)])->field('link_id, uid, total_fee, activation_time')->select()->toArray();

            $activationUids = $newUids = $newUserPayData = $rechargeNumber = $payResult = $registerUserNumData = $activationUserNumData = [];

            if ($userInfo) {
                $activationUids = array_column($userInfo, 'id');

                foreach ($userInfo as $value) {
                    $activationUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            // 注册用户数
            $registerUserData = Db::name('user')->where(['register_date' => date('Ymd', $timeStamp), 'link_id' => $ids])->field('id, link_id')->select()->toArray();
            if ($registerUserData) {
                $newUids = array_column($registerUserData, 'id');
                foreach ($registerUserData as $key => $value) {
                    $registerUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            $newUserNum = [];
            // 当天新用户充值（当期充值）
            $endTime = strtotime(date('Y-m-d'));
            $startTime = $endTime - 86400;
            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                }

                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点百分比值
            $launchAccountData = Db::name('launch_account')->where(['account_id' => $accountIds])->field('account_id, rebate')->select()->toArray();
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            $saveData = [
                'platform' => 2,
                'date' => date('Ymd', time() - 86400),
                'month' => date('Ym', time() - 86400),
                'total_cost' => 0,
                'activation_user_num' => count($activationUids),
                'register_user_num' => count($newUids),
                'current_recharge' => 0,
                'current_recovery' => 0,
                'total_recharge' => 0,
                'total_recovery' => 0,
                'fans_cost' => 0,
                'revenue' => 0,
                'per_capita_contribution' => 0,
                'created_at' => time(),
                'actual_cost' => 0,
                'recharge_user_num' => 0,
                'conversion_rate' => '0%'
            ];

            $totalClickNum = 0; // 所有链接总点击数
            $totalNewUserNumber = 0; // 所有链接新充人数

            foreach ($data as $key => $item) {
                $data[$key]['platform'] = 2;
                $data[$key]['link_id'] = $item['id'];
                $data[$key]['date'] = date('Ymd', time() - 86400);
                $data[$key]['month'] = date('Ym', time() - 86400);

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                $saveData['total_cost'] = $saveData['total_cost'] + $item['cost']; // 总花费
                $saveData['current_recharge'] = $saveData['current_recharge'] + $currentRecharge; // 当天所有链接当期充值


                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数

                $rechargeSum = empty($rechargeNumber[$item['id']]) ? 0 : count($rechargeNumber[$item['id']]); // 充值笔数
                $data[$key]['conversion_number'] = $conversionNumber;
                $data[$key]['recharge_number'] = $rechargeSum;

                $data[$key]['conversion_cost'] = $conversionNumber == 0 ? 0 : round($item['cost'] / $conversionNumber, 2); // 转化成本
                $saveData['recharge_user_num'] = $saveData['recharge_user_num'] + $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $totalNewUserNumber = $totalNewUserNumber + $newUserNumber;

                // 转化率
                $redisKey = config('redis_key.link_same_day_click_num') . date('Ymd', time() - 86400) . '-' . $item['id'];
                $clickNum = $redis->get($redisKey);
                if (empty($clickNum) || empty($newUserNum[$item['id']])) {
                    $data[$key]['conversion_rate'] = '0%';
                } else {
                    $data[$key]['conversion_rate'] = round($newUserNumber / $clickNum * 100, 2) . '%';
                    $totalClickNum = $totalClickNum + $clickNum;
                }

                $data[$key]['register_user_num'] = !empty($registerUserNumData[$item['id']]) ? count($registerUserNumData[$item['id']]) : 0; // 该链接当日注册用户
                $data[$key]['fans_cost'] = !empty($registerUserNumData[$item['id']]) ? round($item['cost'] / count($registerUserNumData[$item['id']]), 2) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = round($currentRecharge, 2);
                $saveData['total_recharge'] = $saveData['total_recharge'] + $currentRecharge; // 总充值


                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献
                $data[$key]['created_at'] = time();

                // 激活用户数
                $data[$key]['activation_user_num'] = !empty($activationUserNumData[$item['id']]) ? count($activationUserNumData[$item['id']]) : 0;
                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } elseif (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                // $actualCost= !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_cost'] = $actualCost;
                $saveData['actual_cost'] = $saveData['actual_cost'] + $actualCost;
                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况 = 累计充值 - 实际花费
                $data[$key]['current_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 当期回收

                unset($data[$key]['id']);
                unset($data[$key]['video_id']);
                unset($data[$key]['video_detail_id']);
                unset($data[$key]['rebate']);
                unset($data[$key]['version']);
                unset($data[$key]['project_id']);
            }
        }

        // 统计在投所有链接每天的投放数据
        $saveData['current_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['current_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 当期回收
        $saveData['total_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['total_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 累计回收
        $saveData['fans_cost'] = !empty($saveData['register_user_num']) ? round($saveData['total_cost'] / $saveData['register_user_num'], 2) : 0; // 粉丝成本
        $saveData['revenue'] = round($saveData['total_recharge'] - $saveData['actual_cost'], 2); // 营收情况
        $saveData['per_capita_contribution'] = !empty($saveData['register_user_num']) ? round($saveData['current_recharge'] / $saveData['register_user_num'], 2) : 0; // 人均贡献
        $saveData['total_cost'] = round($saveData['total_cost'], 2);
        $saveData['current_recharge'] = round($saveData['current_recharge'], 2);
        $saveData['total_recharge'] = round($saveData['total_recharge'], 2);
        $saveData['conversion_rate'] = !empty($totalClickNum) ? round($totalNewUserNumber / $totalClickNum * 100, 2) . '%' : '0%';

        Db::name('delivery_data')->insert($saveData);

        // 统计在投每条链接每天的投放数据
        $bool = Db::name('daily_delivery_data')->insertAll($data);
        return $bool;
    }

    // 统计百度每天投放数据
    public function baiduDailyDeliveryData()
    {
        $linkData = Db::name('link')->where(['link_switch' => 1, 'media_id' => 3])->field('id, video_id, video_detail_id, advertiser_id, version, project_id, rebate')->select()->toArray();

        // 获取统计当天关闭投放的链接数据
        $sql = 'select id, video_id, video_detail_id, advertiser_id, version, project_id, rebate from ly_link where media_id=3 and from_unixtime(release_end_time, "%Y%m%d") = ' . date('Ymd', time() - 86400);
        $linkData1 = Db::query($sql);

        $linkAdvertiserIds = array_column($linkData, 'advertiser_id');
        $newlinkData = [];
        foreach ($linkData1 as $key => $value) {
            if (!in_array($value['advertiser_id'], $linkAdvertiserIds)) {
                $newlinkData[] = $value;
            }
        }
        $linkData = array_merge($linkData, $newlinkData);

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $accessToken = Common::getBaiduAccessToken();
        $hearder['json'] = 1;

        $startDate = date('Y-m-d', time() - 86400);
        $endDate = date('Y-m-d', time() - 86400);
        $data = $accountIds = [];
        $url = 'https://api.baidu.com/json/feed/v1/ReportFeedService/getRealTimeFeedData';
        $subUserListKey = config('baidu.baidu_sub_user_list');
        $subUserList = $redis->hGetAll($subUserListKey);

        foreach ($linkData as $value) {
            if (empty($value['advertiser_id']) || empty($subUserList[$value['advertiser_id']])) {
                continue;
            }

            // 获取成本
            $requestData = [
                'header' => [
                    'userName' => $subUserList[$value['advertiser_id']],
                    'accessToken' => $accessToken
                ],
                'body' => [
                    'realTimeRequestType' => [
                        'performanceData' => ['cost'],
                        'startDate' => $startDate,
                        'endDate' => $endDate,
                        'levelOfDetails' => 2,
                        'reportType' => 700,
                        'unitOfTime' => 5
                    ]
                ]
            ];

            $result = Common::_curl($url, $requestData, 'POST', $hearder);
            $result = json_decode($result, true);

            if ($result['header']['desc'] == 'success' && $result['header']['status'] == 0) {
                $value['cost'] = 0;
                if (!empty($result['body']['data'])) {
                    $value['cost'] = round($result['body']['data'][0]['kpis'][0], 2);
                }

                $data[] = $value;
            } else {
                sleep(60);
                return self::baiduDailyDeliveryData();
            }

            $accountIds[] = $value['advertiser_id'];
        }

        if ($data) {
            $ids = array_column($data, 'id');

            $linkData2 = [];
            foreach ($linkData1 as $item) {
                if (!in_array($item['id'], $ids)) {
                    $linkData2[] = [
                        'id' => $item['id'],
                        'video_id' => $item['video_id'],
                        'video_detail_id' => $item['video_detail_id'],
                        'advertiser_id' => $item['advertiser_id'],
                        'version' => $item['version'],
                        'project_id' => $item['project_id'],
                        'rebate' => $item['rebate'],
                        'cost' => 0
                    ];
                }
            }
            $data = array_merge($data, $linkData2);
            $ids = array_column($data, 'id');

            $timeStamp = time() - 86400;
            $start = date('Y-m-d', $timeStamp) . ' 00:00:00';
            $end = date('Y-m-d', $timeStamp) . ' 23:59:59';
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [$start, $end]]
            ];
            $userInfo = Db::name('user')->where($userWhere)->field('id, link_id')->select()->toArray();
            $payData = Db::name('pay_record')->where(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd', time() - 86400)])->field('link_id, uid, total_fee, activation_time')->select()->toArray();

            $activationUids = $newUids = $newUserPayData = $rechargeNumber = $payResult = $activationUserNumData = $registerUserNumData = [];

            if ($userInfo) {
                $activationUids = array_column($userInfo, 'id');

                foreach ($userInfo as $value) {
                    $activationUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            // 注册用户数
            $registerUserData = Db::name('user')->where(['register_date' => date('Ymd', $timeStamp), 'link_id' => $ids])->field('id, link_id')->select()->toArray();
            if ($registerUserData) {
                $newUids = array_column($registerUserData, 'id');
                foreach ($registerUserData as $key => $value) {
                    $registerUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            $newUserNum = [];
            // 当天新用户充值（当期充值）
            $endTime = strtotime(date('Y-m-d'));
            $startTime = $endTime - 86400;

            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                }

                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            // 获取返点百分比值
            $launchAccountData = Db::name('launch_account')->where(['account_id' => $accountIds])->field('account_id, rebate')->select()->toArray();
            $launchAccount = array_column($launchAccountData, 'rebate', 'account_id');

            $saveData = [
                'platform' => 3,
                'date' => date('Ymd', time() - 86400),
                'month' => date('Ym', time() - 86400),
                'total_cost' => 0,
                'activation_user_num' => count($activationUids),
                'current_recharge' => 0,
                'current_recovery' => 0,
                'total_recharge' => 0,
                'total_recovery' => 0,
                'fans_cost' => 0,
                'revenue' => 0,
                'per_capita_contribution' => 0,
                'created_at' => time(),
                'register_user_num' => count($newUids),
                'actual_cost' => 0,
                'recharge_user_num' => 0,
                'conversion_rate' => '0%'
            ];

            $totalClickNum = 0; // 所有链接总点击数
            $totalNewUserNumber = 0; // 所有链接新充人数

            foreach ($data as $key => $item) {
                $data[$key]['platform'] = 3;
                $data[$key]['link_id'] = $item['id'];
                $data[$key]['date'] = date('Ymd', time() - 86400);
                $data[$key]['month'] = date('Ym', time() - 86400);

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                $saveData['total_cost'] = $saveData['total_cost'] + $item['cost']; // 总花费
                $saveData['current_recharge'] = $saveData['current_recharge'] + $currentRecharge; // 当天所有链接当期充值


                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $rechargeSum = empty($rechargeNumber[$item['id']]) ? 0 : count($rechargeNumber[$item['id']]); // 充值笔数
                $data[$key]['conversion_number'] = $conversionNumber;
                $data[$key]['recharge_number'] = $rechargeSum;
                $data[$key]['conversion_cost'] = $conversionNumber == 0 ? 0 : round($item['cost'] / $conversionNumber, 2); // 转化成本
                $saveData['recharge_user_num'] = $saveData['recharge_user_num'] + $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $totalNewUserNumber = $totalNewUserNumber + $newUserNumber;

                // 转化率
                // $redisKey = config('redis_key.link_same_day_click_num').date('Ymd', time() - 86400).'-'.$item['id'];
                // $clickNum = $redis->get($redisKey);
                // if (empty($clickNum) || empty($newUserNum[$item['id']])) {
                //     $data[$key]['conversion_rate'] = '0%';
                // } else {
                //     $data[$key]['conversion_rate'] = round($newUserNumber / $clickNum * 100, 2) . '%';
                //     $totalClickNum = $totalClickNum + $clickNum;
                // }

                $data[$key]['register_user_num'] = !empty($registerUserNumData[$item['id']]) ? count($registerUserNumData[$item['id']]) : 0; // 该链接当日注册用户
                $data[$key]['fans_cost'] = !empty($registerUserNumData[$item['id']]) ? round($item['cost'] / count($registerUserNumData[$item['id']]), 2) : 0; // 粉丝成本
                // $totalRecharge = empty($payResult[$item['id']]) ? 0 : array_sum($payResult[$item['id']]); // 当天累计充值
                $data[$key]['total_recharge'] = round($currentRecharge, 2);
                $saveData['total_recharge'] = $saveData['total_recharge'] + $currentRecharge; // 总充值

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献
                $data[$key]['created_at'] = time();

                // 激活用户数
                $linkActivationUserNum = !empty($activationUserNumData[$item['id']]) ? count($activationUserNumData[$item['id']]) : 0;
                $data[$key]['activation_user_num'] = $linkActivationUserNum;
                // 转化率
                if (empty($linkActivationUserNum) || empty($newUserNumber)) {
                    $data[$key]['conversion_rate'] = '0%';
                } else {
                    $data[$key]['conversion_rate'] = round($newUserNumber / $linkActivationUserNum * 100, 2) . '%';
                    $totalClickNum = $totalClickNum + $linkActivationUserNum;
                }
                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } elseif (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                // $actualCost = !empty($launchAccount[$item['advertiser_id']]) ? round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2) : 0;
                $data[$key]['actual_cost'] = $actualCost;
                $saveData['actual_cost'] = $saveData['actual_cost'] + $actualCost;
                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况 = 累计充值 - 实际花费
                $data[$key]['current_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 当期回收

                unset($data[$key]['id']);
                unset($data[$key]['video_id']);
                unset($data[$key]['video_detail_id']);
                unset($data[$key]['version']);
                unset($data[$key]['project_id']);
                unset($data[$key]['rebate']);
            }
            // 统计在投所有链接每天的投放数据
            $saveData['current_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['current_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 当期回收
            $saveData['total_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['total_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 累计回收
            $saveData['fans_cost'] = !empty($saveData['register_user_num']) ? round($saveData['total_cost'] / $saveData['register_user_num'], 2) : 0; // 粉丝成本
            $saveData['revenue'] = !empty($saveData['total_recharge']) ? round($saveData['total_recharge'] - $saveData['actual_cost'], 2) : 0; // 营收情况
            $saveData['per_capita_contribution'] = !empty($saveData['register_user_num']) ? round($saveData['current_recharge'] / $saveData['register_user_num'], 2) : 0; // 人均贡献
            $saveData['total_cost'] = round($saveData['total_cost'], 2);
            $saveData['current_recharge'] = round($saveData['current_recharge'], 2);
            $saveData['total_recharge'] = round($saveData['total_recharge'], 2);
            $saveData['conversion_rate'] = !empty($totalClickNum) ? round($totalNewUserNumber / $totalClickNum * 100, 2) . '%' : '0%';

            Db::name('delivery_data')->insert($saveData);

            // 统计在投每条链接每天的投放数据
            $bool = Db::name('daily_delivery_data')->insertAll($data);
            return $bool;
        }

        return 0;
    }

    // 更新投放数据
    public function updateTotalRecharge()
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);

        $startData = date('Ymd', time() - 86400 * 10);

        $data = Db::name('daily_delivery_data')->where([['date', '>', $startData]])->order('date')->select()->toArray();
        // $data = Db::name('daily_delivery_data')->order('date')->select()->toArray();

        $linkIds = array_column($data, 'link_id');
        $date = array_column($data, 'date');

        $payData = Db::name('pay_record')->where(['link_id' => $linkIds, 'activation_date' => $date, 'status' => 1])->select()->toArray();
        $payResult = $rechargeNumber = [];
        foreach ($payData as $key => $value) {
            $payResult[$value['link_id'] . '_' . $value['activation_date']][] = $value['total_fee'];
            $rechargeNumber[$value['link_id'] . '_' . $value['activation_date']][] = $value['uid'];
        }

        $result = [];
        foreach ($data as $key => $value) {

            $total_recharge = empty($payResult[$value['link_id'] . '_' . $value['date']]) ? 0 : array_sum($payResult[$value['link_id'] . '_' . $value['date']]);
            $new_user_number = empty($rechargeNumber[$value['link_id'] . '_' . $value['date']]) ? 0 : count(array_unique($rechargeNumber[$value['link_id'] . '_' . $value['date']]));
            $recharge_number = empty($rechargeNumber[$value['link_id'] . '_' . $value['date']]) ? 0 : count($rechargeNumber[$value['link_id'] . '_' . $value['date']]);
            $revenue = round($total_recharge - $value['actual_cost'], 2);
            $per_capita_contribution = empty($new_user_number) ? 0 : round($total_recharge / $new_user_number, 2);

            Db::name('daily_delivery_data')->where(['id' => $value['id']])->update([
                'total_recharge' => $total_recharge,
                'conversion_number' => $new_user_number,
                'revenue' => $revenue,
                'per_capita_contribution' => $per_capita_contribution,
                'recharge_number' => $recharge_number
            ]);

            $result[] = ['platform' => $value['platform'], 'date' => $value['date'], 'total_recharge' => $total_recharge, 'recharge_user_num' => $new_user_number];
        }

        $delivery_data = Db::name('delivery_data')->where([['date', '>', $startData]])->order('date')->select()->toArray();

        foreach ($delivery_data as $key => $value) {
            $total_recharge = 0;
            $recharge_user_num = 0;
            foreach ($result as $item) {
                if ($value['date'] == $item['date'] && $value['platform'] == $item['platform']) {
                    $total_recharge += $item['total_recharge'];
                    $recharge_user_num += $item['recharge_user_num'];
                }
            }

            $total_recovery = empty($value['actual_cost']) || $value['actual_cost'] == 0.00 ? '0%' : round($total_recharge / $value['actual_cost'] * 100, 2) . '%';
            $revenue = round($total_recharge - $value['actual_cost'], 2);
            $per_capita_contribution = empty($recharge_user_num) ? 0 : round($total_recharge / $recharge_user_num, 2);

            Db::name('delivery_data')->where(['id' => $value['id']])->update([
                'total_recharge' => $total_recharge,
                'total_recovery' => $total_recovery,
                'revenue' => $revenue,
                'per_capita_contribution' => $per_capita_contribution,
                'recharge_user_num' => $recharge_user_num
            ]);
        }
        return json(['msg' => 'success']);
    }

    // 统计每日用户充值消耗数据
    public function statisticsUserRechargeConsume()
    {
        $date = date('Ymd', time() - 86400);
        $startDateTime = date('Y-m-d', time() - 86400) . ' 00:00:00';
        $endDateTime = date('Y-m-d') . ' 00:00:00';

        $linkData = Db::name('link')->where(['link_switch' => 1])->field('id, video_id, video_detail_id, advertiser_id, version, project_id')->select()->toArray();

        $linkIds = array_column($linkData, 'id');

        $userWhere = [
            ['link_id', 'in', $linkIds],
            ['activation_time', 'between', [$startDateTime, $endDateTime]]
        ];
        $userData = Db::name('user')->where($userWhere)->field('id, link_id')->select()->toArray();

        $payData = Db::name('pay_record')->where(['link_id' => $linkIds, 'status' => 1, 'consume_date' => $date, 'activation_date' => $date, 'type' => 1])->field('link_id, uid, total_fee, number')->select()->toArray();
        $totalRecharge = $totalNumber = $rechargeNum = 0;
        $rechargeUserNum = [];
        foreach ($payData as $item) {
            $totalRecharge += $item['total_fee'];
            $totalNumber += $item['number'];
            // $rechargeNum += 1;
            $rechargeUserNum[] = $item['uid'];
        }

        $consumeData = Db::name('watch_pay_record')->where(['link_id' => $linkIds, 'consume_date' => $date])->field('link_id, uid, money, activation_time')->select()->toArray();
        $totalConsume = 0;
        foreach ($consumeData as $item) {
            if ($item['activation_time'] >= $startDateTime && $item['activation_time'] < $endDateTime) {
                $totalConsume += $item['money'];
            }
        }

        $userCount = count($userData);
        $rechargeUserNum = count(array_unique($rechargeUserNum));

        $saveDate = [
            'date' => $date,
            'month' => date('Ym', time() - 86400),
            'activation_user_num' => $userCount,
            'recharge_user_num' => $rechargeUserNum,
            'recharge_money' => round($totalRecharge, 2),
            'total_recharge' => round($totalRecharge, 2),
            'consume_k_coins' => $totalConsume,
            'account_balance' => $totalNumber - $totalConsume,
            'per_capita_recharge' => round($totalRecharge / $rechargeUserNum, 2),
            'per_capita_consume' => round($totalConsume / $rechargeUserNum)
        ];

        return Db::name('user_recharge_consume_analysis')->insert($saveDate);
    }

    // 分销商分成数据每日统计(每天凌晨统计昨天的数据)
    public function distributorsSharing()
    {
        // $dateStr = $input->getArgument('date_str');
        $dateStr = date('Y-m-d', time() - 86400 * 24);
        if ($dateStr) {
            $dateTime = date('Ymd', strtotime($dateStr));
            $month = date('Ym', strtotime($dateStr));
        } else {
            $dateTime = date('Ymd', time() - 86400);
            $month = date('Ym', time() - 86400);
        }

        // $doneTaskCount = DistributorsSharingStatistics::where('date',$dateTime)->count();
        //任务已经跑过
        // if ($doneTaskCount > 0){
        //     return 0;
        // }
        $distributor = Db::name('responsibility_person')->where(['is_distributor' => 1])->field('id, name, commission_scale, scale, company_id,wechat_applet_commission_scale')->select()->toArray();
        $pids = array_column($distributor, 'id');
        $pitcher = Db::name('responsibility_person')->where(['pid' => $pids])->field('id, pid')->select()->toArray();

        $pitcherIds = array_column($pitcher, 'id');

        $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

        $linkIds = array_column($linkData, 'id');

        $distributorArray = [];
        foreach ($pitcher as $item) {
            $distributorArray[$item['pid']][] = $item['id'];
        }
        $link = [];
        foreach ($linkData as $value) {
            $link[$value['responsibility_person_id']][] = $value['id'];
        }

        $distributorData = [];
        foreach ($distributorArray as $key => $value) {
            $linkIdArray = [];
            foreach ($value as $pitcherId) {
                if (!empty($link[$pitcherId])) {
                    $linkIdArray = array_merge($linkIdArray, $link[$pitcherId]);
                }
            }
            $distributorData[$key] = $linkIdArray;
        }

        if ($dateStr) {
            $date = date('Y-m-d', strtotime($dateStr));
        } else {
            $date = date('Y-m-d', time() - 86400);
        }
        $startTime = strtotime($date);
        $endTime = strtotime($date . ' 23:59:59');
        $where = [
            ['status', '=', 1],
            ['pay_time', '>=', $startTime],
            ['pay_time', '<=', $endTime],
            ['link_id', 'in', $linkIds]
        ];

        $payData = Db::name('pay_record')->where($where)->field('link_id, total_fee, pay_merchant, device_type')->select()->toArray();
        $rechargeData = [];
        $virtualRechargeData = [];
        $commonRechargeData = [];
        foreach ($payData as $value) {
            $rechargeData[$value['link_id']][] = $value['total_fee'];
            if ($value['pay_merchant'] == PayRecord::PAY_MERCHANT_VIRTUALPAYMENT && $value['device_type'] == PayRecord::DEVICE_TYPE_ANDROID) {
                $virtualRechargeData[$value['link_id']][] = $value['total_fee'];
            } else {
                $commonRechargeData[$value['link_id']][] = $value['total_fee'];
            }
        }

        // 退款金额
        $where = [
            ['rr.status', '=', 1],
            ['rr.refund_time', '>=', $date . ' 00:00:00'],
            ['rr.refund_time', '<=', $date . ' 23:59:59']
        ];
        $refundData = Db::name('refund_record')->alias('rr')->leftjoin('pay_record pr', 'pr.id = rr.pay_id')->where($where)->field('rr.link_id, rr.refund_price, rr.pay_merchant, pr.device_type')->select()->toArray();
        $refund = [];
        $virtualRefund = [];
        $commonRefund = [];
        foreach ($refundData as $key => $value) {
            $refund[$value['link_id']][] = $value['refund_price'];
            if ($value['pay_merchant'] == PayRecord::PAY_MERCHANT_VIRTUALPAYMENT && $value['device_type'] == PayRecord::DEVICE_TYPE_ANDROID) {
                $virtualRefund[$value['link_id']][] = $value['refund_price'];
            } else {
                $commonRefund[$value['link_id']][] = $value['refund_price'];
            }
        }

        // 统计分销商充值以及分成、手续费
        $distributorResult = array_column($distributor, null, 'id');

        $saveData = [];

        foreach ($distributorData as $distributorId => $linkId) {
            $rechargePrice = 0;
            $refundPrice = 0;
            $virtualRechargePrice = 0;
            $virtualRefundPrice = 0;
            $commonRechargePrice = 0;
            $commonRefundPrice = 0;

            foreach ($linkId as $id) {
                $rechargePrice += !empty($rechargeData[$id]) ? array_sum($rechargeData[$id]) : 0;
                $virtualRechargePrice += !empty($virtualRechargeData[$id]) ? array_sum($virtualRechargeData[$id]) : 0;
                $refundPrice += !empty($refund[$id]) ? array_sum($refund[$id]) : 0;
                $virtualRefundPrice += !empty($virtualRefund[$id]) ? array_sum($virtualRefund[$id]) : 0;
                $commonRechargePrice += !empty($commonRechargeData[$id]) ? array_sum($commonRechargeData[$id]) : 0;
                $commonRefundPrice += !empty($commonRefund[$id]) ? array_sum($commonRefund[$id]) : 0;
            }
            //非虚拟支付手续费
            $commonCommission = round(($commonRechargePrice - $commonRefundPrice) * $distributorResult[$distributorId]['commission_scale'] / 100, 2);
            //虚拟支付手续费
            $virtualCommission = round(($virtualRechargePrice - $virtualRefundPrice) * $distributorResult[$distributorId]['wechat_applet_commission_scale'] / 100, 2);
            //总手续费
            $commission =  round($commonCommission + $virtualCommission, 2);
            //非虚拟支付分成比率
            $scale = round((1 - $distributorResult[$distributorId]['scale'] / 100), 2);
            //非虚拟支付分成金额
            $commonSharingAmount = round(($commonRechargePrice - $commonRefundPrice - $commonCommission) * $scale, 2);
            //虚拟支付分成比率
            $virtualScale = config('distributor_setting.virtual_scale');
            //虚拟支付分成金额
            $virtualSharingAmount = round(($virtualRechargePrice - $virtualRefundPrice - $virtualCommission) * $virtualScale, 2);
            //分销商总分成金额
            $sharingAmount = round($commonSharingAmount + $virtualSharingAmount, 2);
            //腾讯虚拟支付通道费-算到六翼成本
            $virtualCommissionCostByLiuyi = round(($virtualRechargePrice - $virtualRefundPrice) * 0.1, 2);
            //虚拟支付六翼分成 = （虚拟充值-退款）*0.2-虚拟支付通道费
            $virtualLySharingAmount = ($virtualRechargePrice - $virtualRefundPrice) * 0.2 - $virtualCommissionCostByLiuyi;
            //非虚拟支付六翼分成金额=非虚拟充值-退款-千8通道费）*0.15
            $commonLySharingAmount = ($commonRechargePrice - $commonRefundPrice  - $commonCommission) * 0.15;

            //六翼分成金额
            $lySharingAmount = round($virtualLySharingAmount + $commonLySharingAmount, 2);
            //round($rechargePrice - $refundPrice - $sharingAmount - $commission - $virtualCommissionCostByLiuyi, 2);

            Db::name('distributors_sharing_statistics')->where(['date' => $dateTime, 'distributor_id' => $distributorId])->update([
                // 'date' => $dateTime,
                // 'month' => $month,
                // 'name' => $distributorResult[$distributorId]['name'],
                // 'distributor_id' => $distributorId,
                // 'company_name' => Db::name('company')->where('id', $distributorResult[$distributorId]['company_id'])->field('name')->find()['name'],
                'recharge_price' => round($rechargePrice, 2),
                'refund_price' => round($refundPrice, 2),
                'commission' => $commission,
                'scale' => $scale,
                'sharing_amount' => $sharingAmount,
                'ly_sharing_amount' => $lySharingAmount,
                'virtual_recharge_price' => round($virtualRechargePrice, 2),
                'virtual_refund_price' => round($virtualRefundPrice, 2),
                'virtual_commission' => $virtualCommission,
                'virtual_scale' => $virtualScale,
                'common_recharge_price' => round($commonRechargePrice, 2),
                'common_refund_price' => round($commonRefundPrice, 2),
                'common_scale' => $scale,
                'ad_incentive_amount' => round(($virtualRechargePrice - $virtualRefundPrice) * 0.05, 2),
                'virtual_amount' => $virtualSharingAmount,
                'common_amount' => $commonSharingAmount,
                'common_commission' => $commonCommission,
                'created_at' => time(),
            ]);
        }
        // dump($saveData);die;
        // $bool = Db::name('distributors_sharing_statistics')->insertAll($saveData);
        return true;
    }

    // 生成分销结算列表(每周三生成上一周结算数据)
    public function generateDistributionSettlementList()
    {
        $date = date('Y-m-d');
        $w = date("w", strtotime($date)); // 星期
        if ($w == 0) $w = 7; // 0=周日
        $n = $w - 1 + 7; // 上周一
        $lastMondayDate = date('Y-m-d', strtotime("-{$n} days", strtotime($date)));
        $lastSundayDate = date('Y-m-d', strtotime($lastMondayDate) + 6 * 86400);

        $startDate = date('Ymd', strtotime($lastMondayDate));
        $endDate = date('Ymd', strtotime($lastSundayDate));

        $where = [
            ['date', '>=', $startDate],
            ['date', '<=', $endDate]
        ];
        $distributorsSharingStatisticsData = Db::name('distributors_sharing_statistics')->where($where)->select()->toArray();

        $settlementData = $distributorIds = [];
        foreach ($distributorsSharingStatisticsData as $key => $value) {
            $settlementData[$value['distributor_id']][] = $value;
            $distributorIds[] = $value['distributor_id'];
        }

        // 分销商数据
        $distributorIds = array_unique($distributorIds);
        $distributor = Db::name('responsibility_person')->where(['is_distributor' => 1, 'id' => $distributorIds])->field('id, company_id')->select()->toArray();
        $companyIds = array_column($distributor, 'company_id', 'id');

        $saveData = [];
        foreach ($settlementData as $key => $value) {
            $settlementPrice = 0;
            foreach ($value as $item) {
                $name = $item['company_name'];
                $settlementPrice += $item['sharing_amount'];
            }
            $companyData = Db::name('company')->where('id', $companyIds[$key])->field('tax_rate, collection_account, bank_name, name, payee, payment_method')->find();
            // dump($companyData);die;
            $saveData[] = [
                'distributor_id' => $key,
                'name' => $name,
                'start_date' => $lastMondayDate,
                'end_date' => $lastSundayDate,
                'settlement_price' => $settlementPrice,
                'status' => 1,
                'collection_account' => $companyData['collection_account'],
                'payee' => $companyData['payee'],
                'payment_method' => $companyData['payment_method'],
                'bank_name' => $companyData['bank_name'],
                'tax_rate' => $companyData['tax_rate'] . '%'
                // 'payment_time' =>
            ];
        }

        $bool = Db::name('distribution_settlement')->insertAll($saveData);
        return $bool;
    }

    // 每天统计每部短剧每个充值模板的人均和充值(按充值短剧)
    public function statisticsVideoPerCapita()
    {
        $date = date('Ymd', time() - 86400);
        // dump($date);die;
        $data = Db::name('pay_record')->alias('a')->join('link b', 'a.link_id = b.id')->join('recharge_template c', 'b.recharge_template_id = c.id')->where(['a.status' => 1, 'a.consume_date' => $date])->join('videos d', 'd.id = a.video_id')->field('a.total_fee, a.uid, a.video_id, c.type, c.name as template_name, d.name as video_name, b.recharge_template_id')->select()->toArray();

        $result = [];
        foreach ($data as $key => $value) {
            $result[$value['video_id'] . '_' . $value['recharge_template_id']][] = $value;
        }

        $saveData = [];
        $month = date('Ym', time() - 86400);
        foreach ($result as $key => $value) {

            $totalPrice = 0;
            $uids = [];

            foreach ($value as $item) {
                $totalPrice += $item['total_fee'];
                $uids[] = $item['uid'];
            }

            list($videoId, $rechargeTemplateId) = explode('_', $key);
            $saveData[] = [
                'recharge_price' => $totalPrice,
                'recharge_people_num' => count(array_unique($uids)),
                'video_id' => $videoId,
                'video_name' => $value[0]['video_name'],
                'recharge_template_id' => $rechargeTemplateId,
                'recharge_template_name' => $value[0]['template_name'],
                'recharge_template_type' => $value[0]['type'],
                'date' => $date,
                'month' => $month,
                'created_at' => time()
            ];
        }

        $bool = Db::name('statistics_video_recharge_data')->insertAll($saveData);
        return $bool;
    }

    // 获取抖音在投链接项目ID用于实时
    public function getTiktokProjectByRealTime()
    {
        // 分销商链接不查询
        $distributorResponsibilityPerson = Db::name('responsibility_person')->where(['pid' => Db::raw('IS NOT NULL')])->field('id')->select()->toArray();

        $distributorResponsibilityPersonIds = array_column($distributorResponsibilityPerson, 'id');

        $linkData = Db::name('link')->where([['media_id', '=', 1], ['link_switch', '=', 1], ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds]])->field('id, advertiser_id, subject_id')->select()->toArray();

        $appId = config('tiktok.huge_amount.app_id');
        $secret = config('tiktok.huge_amount.secret');
        $accessToken = Common::getHugeAmountAccessToken($appId, $secret);

        $appId1 = config('tiktok.huge_amount_yaodao.app_id');
        $secret1 = config('tiktok.huge_amount_yaodao.secret');
        $accessToken1 = Common::getHugeAmountAccessToken($appId1, $secret1);

        $appId24 = config('tiktok.huge_amount_xingcan.app_id');
        $secret24 = config('tiktok.huge_amount_xingcan.secret');
        $accessToken24 = Common::getHugeAmountAccessToken($appId24, $secret24);

        $hearder['json'] = 1;
        $url = 'https://api.oceanengine.com/open_api/v3.0/project/list/';

        $saveData = [];
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }

            if ($value['subject_id'] == 8) {
                $hearder['headers'] = ['Access-Token:' . $accessToken1];
            } elseif ($value['subject_id'] == 24) {
                $hearder['headers'] = ['Access-Token:' . $accessToken24];
            } else {
                $hearder['headers'] = ['Access-Token:' . $accessToken];
            }

            // 获取项目ID
            $getProjectBody = [
                'advertiser_id' => intval($value['advertiser_id']),
                'fields' => ['project_id'],
                'page_size' => 100
            ];

            $getProjectRequestData = [];
            foreach ($getProjectBody as $k1 => $val1) {
                $getProjectRequestData[$k1] = is_string($val1) ? $val1 : json_encode($val1);
            }

            $getProjectResult = Common::_curl($url, $getProjectRequestData, 'GET', $hearder);
            $getProjectResult = json_decode($getProjectResult, true);

            if (!isset($getProjectResult['code']) || !empty($getProjectResult['code'])) {
                Log::error('******' . json_encode($getProjectResult) . ' --//-- ' . '链接ID：' . $value['id'] . '-----');
                continue;
            }

            if (empty($getProjectResult['data']['list'])) {
                continue;
            }

            $string = '';
            foreach ($getProjectResult['data']['list'] as $val2) {
                $string .= $val2['project_id'] . ',';
            }
            $projectIdString = substr($string, 0, -1);
            $projectId = explode(',', $projectIdString);

            if (!empty($projectId)) {
                $saveData[] = [
                    'id' => $value['id'],
                    'project_id' => $projectIdString
                ];
            }

            sleep(3);
        }

        $model = new Link();
        $bool = $model->saveAll($saveData);
        return $bool;
    }

    // 获取抖音项目ID和花费用于实时
    public function getTiktokCostByRealTime()
    {
        // 分销商链接不查询
        $distributorResponsibilityPerson = Db::name('responsibility_person')->where(['pid' => Db::raw('IS NOT NULL')])->field('id')->select()->toArray();

        $distributorResponsibilityPersonIds = array_column($distributorResponsibilityPerson, 'id');

        $linkData = Db::name('link')->where([['media_id', '=', 1], ['link_switch', '=', 1], ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds]])->field('id, video_id, video_detail_id, advertiser_id, responsibility_person_id, version, project_id, rebate, echo_rate, subject_id, created_at')->select()->toArray();

        $appId = config('tiktok.huge_amount.app_id');
        $secret = config('tiktok.huge_amount.secret');
        $accessToken = Common::getHugeAmountAccessToken($appId, $secret);

        $appId1 = config('tiktok.huge_amount_yaodao.app_id');
        $secret1 = config('tiktok.huge_amount_yaodao.secret');
        $accessToken1 = Common::getHugeAmountAccessToken($appId1, $secret1);

        $appId24 = config('tiktok.huge_amount_xingcan.app_id');
        $secret24 = config('tiktok.huge_amount_xingcan.secret');
        $accessToken24 = Common::getHugeAmountAccessToken($appId24, $secret24);

        $hearder['json'] = 1;
        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $url2 = 'https://api.oceanengine.com/open_api/v3.0/report/custom/get/';

        $queryDate = [];
        for ($i = 1; $i < 4; $i++) {
            $queryDate[] = date('Ymd', time() - $i * 86400);
        }
        $createTime = strtotime($startDate) - 3 * 86400;

        $redisData = $linkIds = [];
        foreach ($linkData as $value) {
            if (empty($value['advertiser_id']) || empty($value['project_id'])) {
                continue;
            }

            if ($value['subject_id'] == 8) {
                $hearder['headers'] = ['Access-Token:' . $accessToken1];
            } elseif ($value['subject_id'] == 24) {
                $hearder['headers'] = ['Access-Token:' . $accessToken24];
            } else {
                $hearder['headers'] = ['Access-Token:' . $accessToken];
            }

            $projectId = explode(',', $value['project_id']);

            // 获取花费
            $body = [
                'dimensions' => ['stat_time_day', 'cdp_project_name'],
                'advertiser_id' => $value['advertiser_id'], // 广告账户id
                'start_time' => $startDate,
                'end_time' => $endDate,
                'metrics' => ['stat_cost'],
                'order_by' => [
                    [
                        'field' => 'stat_time_day',
                        'type' => 'DESC'
                    ]
                ],
                'filters' => [
                    [
                        'field' => 'cdp_project_id',
                        'type' => 3,
                        'operator' => 1,
                        'values' => $projectId // 项目id
                    ]
                ]
            ];

            $requestData = [];
            foreach ($body as $k => $val) {
                $requestData[$k] = is_string($val) ? $val : json_encode($val);
            }

            $result = Common::_curl($url2, $requestData, 'GET', $hearder);
            $result = json_decode($result, true);

            if (!empty($result['code'])) {
                Log::error('******' . json_encode($result) . ' --//-- ' . '链接ID：' . $value['id'] . '-----');
                continue;
            }

            $cost = 0;
            // if (!empty($result['data']['rows'])) {
            //     foreach ($result['data']['rows'] as $key => $item) {
            //         $value['cost'] += $item['metrics']['stat_cost'];
            //     }
            // }
            if (!empty($result['data']['total_metrics'])) {
                $cost = $result['data']['total_metrics']['stat_cost'];
            }

            // 连续三天为0的消耗关闭链接投放 并且链接创建时间是3天前
            if (empty(intval($cost)) && $value['created_at'] < $createTime) {
                $historyCost = Db::name('daily_delivery_data')->where(['date' => $queryDate, 'link_id' => $value['id']])->sum('cost');
                if (empty(ceil($historyCost))) {
                    $linkIds[] = $value['id'];
                    continue;
                }
            }

            $redisData[$value['id']] = strval(round($cost, 2));
            sleep(2);
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redis->set(config('redis_key.tiktok_real_time_cost') . date('Ymd'), json_encode($redisData), 3600);

        if (!empty($linkIds)) {
            Db::name('link')->where(['id' => $linkIds])->update(['link_switch' => 0]);
        }
        return count($redisData);
    }

    //
    public function takeTurnsUpdating()
    {
        $videoData = Db::name('videos')->where([['drama_id', '>', 0]])->field('drama_id, id')->order('id desc')->select()->toArray();
        $videoIds = array_column($videoData, 'id');

        if (count($videoIds)) {
            $number = count($videoIds);
            $limit = 10;
            $page = intval(ceil($number / $limit));
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(7);

        $frequency = $redis->get('video-request-frequency');
        if (empty($frequency)) {
            $frequency = 1;
            $redis->set('video-request-frequency', 2, 900);
        } elseif ($frequency > $page) {
            $frequency = 1;
            $redis->set('video-request-frequency', 2, 900);
        } else {
            $redis->set('video-request-frequency', $frequency + 1, 900);
        }
        return self::updateWechatVideoPlayUrl($frequency, $limit);
    }

    // 更新腾讯微信端短剧播放地址
    public function updateWechatVideoPlayUrl($page = 1, $limit = 10)
    {
        $appletData = Db::name('applet')->where(['id' => 1])->field('id, app_id, app_secret')->find();

        $token = Common::getWechatAppletAccessToken($appletData['app_id'], $appletData['app_secret'], $appletData['id']);

        $params = Request::param();

        if (!empty($params['drama_id'])) {
            $dramaId = $params['drama_id'];
            $videoData = Db::name('videos')->where(['drama_id' => $dramaId])->field('drama_id, id')->select()->toArray();
        } else {
            $offset = ($page - 1) * $limit;
            $videoData = Db::name('videos')->where([['drama_id', '>', 0]])->field('drama_id, id')->order('id desc')->limit($offset, $limit)->select()->toArray();
        }

        $url = 'https://api.weixin.qq.com/wxa/sec/vod/listmedia?access_token=' . $token;

        $videoIds = array_column($videoData, 'id');
        $redis = Cache::store('redis')->handler();

        $videoDetailData = Db::name('video_details')->where(['video_id' => $videoIds])->field('id, video_id, sort')->select()->toArray();

        $videoDetail = [];
        foreach ($videoDetailData as $value) {
            $videoDetail[$value['video_id'] . '_' . $value['sort']] = $value['id'];
        }

        $saveData = [];

        // 获取媒资播放链接
        $getPlayUrl = 'https://api.weixin.qq.com/wxa/sec/vod/getmedialink?access_token=' . $token;

        try {
            foreach ($videoData as $key => $value) {
                // 获取微信短剧播放地址
                $wechatVideoData = Common::curlPostRequest($url, json_encode(['drama_id' => $value['drama_id']]), ['Content-Type:application/json']);

                $wechatVideoData = json_decode($wechatVideoData, true);

                if (!empty($wechatVideoData['errcode'])) {
                    Log::error('******' . json_encode($wechatVideoData) . ' --//-- ' . '微信短剧剧目ID：' . $value['drama_id'] . '-----');
                }

                $mediaInfoList = $wechatVideoData['media_info_list'];
                // dump($mediaInfoList);die;

                $total = $wechatVideoData['total_count'];
                if ($total / 100 > 1) {
                    // 总页数
                    $totalPage = ceil($total / 100);

                    for ($i = 1; $i < $totalPage; $i++) {
                        $body = [
                            'drama_id' => $value['drama_id'],
                            'offset' => 100 * $i
                        ];

                        $wechatVideoData = Common::curlPostRequest($url, json_encode($body), ['Content-Type:application/json']);

                        $wechatVideoData = json_decode($wechatVideoData, true);

                        if (!empty($wechatVideoData['errcode'])) {
                            Log::error('******' . json_encode($wechatVideoData) . ' --//-- ' . '微信短剧剧目ID：' . $value['drama_id'] . '-----');
                        }

                        $mediaInfoList = array_merge($mediaInfoList, $wechatVideoData['media_info_list']);
                    }
                }

                foreach ($mediaInfoList as $item) {

                    $mediaId = $item['media_id'];
                    $requestBody = [
                        'media_id' => $mediaId,
                        't' => time() + 7180
                    ];
                    $wechatVideoPlayData = Common::curlPostRequest($getPlayUrl, json_encode($requestBody), ['Content-Type:application/json']);

                    $wechatVideoPlayData = json_decode($wechatVideoPlayData, true);

                    if (!empty($wechatVideoPlayData['errcode']) || empty($wechatVideoPlayData['media_info'])) {
                        Log::error('******' . json_encode($wechatVideoPlayData) . ' --//-- ' . '媒资ID：' . $mediaId . '-----');
                    }

                    preg_match('/(.*?)[-|\(](\d+)\)?/', $item['name'], $matches);

                    if (!$matches) {
                        preg_match('/(.*?)-第(\d+)/', $item['name'], $matches);
                        if (!$matches) {
                            throw new \Exception(sprintf('/(.*?)[-|\(](\d+)\)?/ 或 /(.*?)-第(\d+)/ 正则匹配失败剧名:%s', $item['name']));
                        }
                    }

                    $name = $matches[1];
                    $sort = intval($matches[2]);

                    $saveData[] = [
                        'id' => $videoDetail[$value['id'] . '_' . $sort],
                        'url' => $wechatVideoPlayData['media_info']['hls_url']
                    ];
                }
            }
        } catch (\Exception $e) {
            Log::error('****** 更新腾讯微信端短剧播放地址异常 --//-- ：' . $e->getLine() . '行；' . $e->getMessage() . '-----');
            return json(['msg' => $e->getMessage()]);
        }

        $model = new VideoDetails();
        $bool = $model->saveAll($saveData);

        if ($bool) {
            // 清理redis数据
            $redis->select(7);
            foreach ($videoIds as $videoId) {
                $key = config('redis_key.get_all_video_data_by_video_id') . $videoId;
                $key1 = config('redis_key.get_video_data_by_video_id') . $videoId;
                $key2 = config('redis_key.get_kwai_video_data_by_video_id') . $videoId;
                $redis->del($key);
                $redis->del($key1);
                $redis->del($key2);
            }
        }
        return json(['msg' => 'success']);
    }

    // 同步快手小程序订单
    public function syncKwaiOrder()
    {
        $orderData = Db::name('pay_record')->where(['is_settlement' => 0, 'source' => 3, 'status' => 1])->field('id, uid, order_no, created_at')->select()->toArray();
        // 获取用户信息
        $uids = array_column($orderData, 'uid');
        $userData = Db::name('user')->where(['id' => $uids])->field('id, open_id')->select()->toArray();
        $user = [];
        foreach ($userData as $key => $value) {
            $user[$value['id']] = $value['open_id'];
        }

        $appletData = Db::name('applet')->where(['type' => 3])->field('app_id, app_secret')->find();
        $accessToken = Common::getKwaiAppletAccessToken($appletData['app_id'], $appletData['app_secret']);

        $url = 'https://open.kuaishou.com/openapi/mp/developer/order/v1/report?app_id=' . $appletData['app_id'] . '&access_token=' . $accessToken;

        $uploadUrl = 'https://open.kuaishou.com/openapi/mp/developer/file//img/uploadWithUrl?app_id=' . $appletData['app_id'] . '&access_token=' . $accessToken . '&url=https://shortplay.sybyn.top/static/23cffcc69be52d5a52a9601165fb495.png';

        $uploadResult = Common::curlRequest($uploadUrl, 'POST');

        $result = json_decode($uploadResult, true);
        if ($result['result'] == 1) {
            $productCoverImgId = $result['data']['imgId'];
        } else {
            return ['message' => $result['error_msg']];
        }

        $saveData = [];
        foreach ($orderData as $key => $item) {
            // 订单同步
            $requestData = [
                'out_biz_order_no' => $item['order_no'],
                'out_order_no' => $item['order_no'],
                'open_id' => $user[$item['uid']],
                'order_create_time' => $item['created_at'],
                'order_status' => 11,
                'order_path' => '/pages/recharge/recharge',
                'product_cover_img_id' => $productCoverImgId
            ];

            $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

            $result = json_decode($result, true);

            if ($result['result'] != 1) {
                // 同步异常
                $saveData[] = [
                    'order_no' => $item['order_no'],
                    'uid' => $item['uid'],
                    'pay_id' => $item['id'],
                    'sync_status' => 2,
                    'sync_error_msg' => $result['error_msg'],
                    'created_at' => time()
                ];
            } else {
                $saveData[] = [
                    'order_no' => $item['order_no'],
                    'uid' => $item['uid'],
                    'pay_id' => $item['id'],
                    'sync_status' => 1,
                    'created_at' => time()
                ];
            }
        }

        $num = Db::name('kwai_order_sync_settlement')->insertAll($saveData);
        return json(['code' => 1, 'message' => $num]);
    }

    // 快手小程序订单结算
    public function settlementKwaiOrder()
    {
        $orderData = Db::name('kwai_order_sync_settlement')->where(['settlement_status' => 0])->field('order_no, pay_id')->select()->toArray();
        // $orderData = Db::name('kwai_order_sync_settlement')->where([['id', '>', 101], ['id', '<', 201]])->field('order_no, pay_id')->select()->toArray();

        $appletData = Db::name('applet')->where(['type' => 3])->field('app_id, app_secret')->find();
        $accessToken = Common::getKwaiAppletAccessToken($appletData['app_id'], $appletData['app_secret']);
        $url = 'https://open.kuaishou.com/openapi/mp/developer/epay/settle?app_id=' . $appletData['app_id'] . '&access_token=' . $accessToken;

        foreach ($orderData as $key => $value) {

            $settleNo = date('YmdHis') . rand(1000, 10000);

            $requestData = [
                'out_order_no' => $value['order_no'],
                'out_settle_no' => $settleNo,
                'reason' => '已支付订单结算',
                'notify_url' => 'https://' . config('app.app_host') . '/admin/finance/settlementCallback'
            ];

            $sign = self::sign($requestData, $appletData);
            $requestData['sign'] = $sign;

            $prepayData = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

            $result = json_decode($prepayData, true);

            if (isset($result['result']) && $result['result'] == 1) {

                Db::name('pay_record')->where(['id' => $value['pay_id']])->update([
                    'is_settlement' => 1,
                    'updated_at' => time()
                ]);

                Db::name('kwai_order_sync_settlement')->where(['order_no' => $value['order_no']])->update([
                    'settlement_status' => 1,
                    'settle_no' => $result['settle_no'],
                    'updated_at' => time()
                ]);
            } else {

                Db::name('kwai_order_sync_settlement')->where(['order_no' => $value['order_no']])->update([
                    'settlement_status' => 2,
                    'settlement_error_msg' => $result['error_msg'],
                    'settle_no' => $settleNo,
                    'updated_at' => time()
                ]);
            }
        }

        return json(['code' => 1, 'message' => '结算成功']);
    }

    // 签名
    public function sign($body = [], $appletData = [])
    {
        $body['app_id'] = $appletData['app_id'];
        ksort($body);
        $string = '';
        foreach ($body as $key => $value) {
            $string .= $key . '=' . $value . '&';
        }
        $string = substr($string, 0, strlen($string) - 1) . $appletData['app_secret'];
        return md5($string);
    }

    // 生成广告金列表列表(每周一生成上一周广告金数据，所选时间T-3)
    public function generateAdFundsList()
    {
        $date = date('Y-m-d');
        $w = date("w", strtotime($date)); // 星期
        if ($w == 0) $w = 7; // 0=周日
        $n = $w - 1 + 7 + 3; // 上周一减3天
        $lastMondayDate = date('Y-m-d', strtotime("-{$n} days", strtotime($date)));
        $lastSundayDate = date('Y-m-d', strtotime($lastMondayDate) + 6 * 86400);

        $startDate = date('Ymd', strtotime($lastMondayDate));
        $endDate = date('Ymd', strtotime($lastSundayDate));
        $where = [
            ['a.consume_date', '>=', $startDate],
            ['a.consume_date', '<=', $endDate],
            ['a.pay_merchant', '=', 15],
            ['a.status', '=', 1],
            ['a.link_id', '>=', 1],

        ];
        $payRecordData = Db::name('pay_record')->alias('a')->leftjoin('link b', 'a.link_id = b.id')->leftjoin('responsibility_person c', 'b.responsibility_person_id = c.id')->leftjoin('company d', 'c.company_id = d.id')->leftjoin('user t1', 'a.uid = t1.id')->leftjoin('applet t2', 't1.applet_id = t2.id')->leftjoin('refund_record t3', 'a.order_no = t3.order_no')->where($where)->field('d.id as company_id,d.name as company_name, t2.id as applet_id ,t2.name as applet_name,a.total_fee as price,a.order_no,t3.refund_price')->group('a.order_no')->order('t3.status asc')->select()->toArray();
        //根据对应的条件进行组装

        $settlementData = $appletIds = [];
        foreach ($payRecordData as $key => $value) {
            $settlementData[$value['applet_id']][] = $value;
            $appletIds[] = $value['applet_id'];
            $companyIds[] = $value['company_id'];
        }

        $settlementData2 = $settlementData3 = $appletIds2 = [];
        foreach ($settlementData as $keyD2 => $valueD2) {
            $settlementData3 = [];
            foreach ($valueD2 as $keyD3 => $valueD3) {
                if ($valueD3['applet_id'] == $keyD2) {
                    $settlementData3[$valueD3['company_id']][] = $valueD3;
                }
            }
            if (!empty($settlementData3)) {
                $settlementData2[$keyD2] = $settlementData3;
            }
        }

        //统计金额和退款。并结算广告金（腾讯广告金：结算周期T-3内的(订单充值金额-退款)*5% ）
        $saveData = [];
        foreach ($settlementData2 as $key1 => $value1) {
            $settlementPrice = 0;
            $settlementRefundPrice = 0;
            foreach ($value1 as $item1) {

                $settlementPrice = array_sum(array_column($item1, 'price'));
                $settlementRefundPrice = array_sum(array_column($item1, 'refund_price'));
                if (!empty($settlementPrice) && $settlementPrice > 0) {
                    $tx_ad_price = ($settlementPrice - $settlementRefundPrice) * 0.05;
                    $saveData[] = [
                        'company_id' => $item1[0]['company_id'],
                        'company_name' => $item1[0]['company_name'],
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                        'price' => $settlementPrice,
                        'refund_price' => $settlementRefundPrice,
                        'tx_ad_price' => $tx_ad_price,
                        'applet_id' => $item1[0]['applet_id'],
                        'applet_name' => $item1[0]['applet_name']
                    ];
                }
            }
        }
        $bool = Db::name('ad_funds')->insertAll($saveData);
        return $bool;
    }

    // 分销商H5短信分成数据每日统计(每天凌晨统计昨天的数据)
    public function distributorsSmsSharing()
    {
        $distributor = Db::name('responsibility_person')->where(['is_distributor' => 1])->field('id, name, commission_scale, scale, company_id')->select()->toArray();
        $pids = array_column($distributor, 'id');
        $pitcher = Db::name('responsibility_person')->where(['pid' => $pids])->field('id, pid')->select()->toArray();

        $pitcherIds = array_column($pitcher, 'id');

        $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

        $linkIds = array_column($linkData, 'id');

        $distributorArray = [];
        foreach ($pitcher as $item) {
            $distributorArray[$item['pid']][] = $item['id'];
        }
        $link = [];
        foreach ($linkData as $value) {
            $link[$value['responsibility_person_id']][] = $value['id'];
        }

        $distributorData = [];
        foreach ($distributorArray as $key => $value) {
            $linkIdArray = [];
            foreach ($value as $pitcherId) {
                if (!empty($link[$pitcherId])) {
                    $linkIdArray = array_merge($linkIdArray, $link[$pitcherId]);
                }
            }
            $distributorData[$key] = $linkIdArray;
        }

        $date = date('Y-m-d', time() - 86400);
        $startTime = strtotime($date);
        $endTime = strtotime($date . ' 23:59:59');
        $where = [
            ['status', '=', 1],
            ['source', '=', 6],
            ['pay_time', '>=', $startTime],
            ['pay_time', '<=', $endTime],
            ['link_id', 'in', $linkIds]
        ];

        $payData = Db::name('pay_record')->where($where)->field('link_id, total_fee')->select()->toArray();
        $rechargeData = [];
        foreach ($payData as $value) {
            $rechargeData[$value['link_id']][] = $value['total_fee'];
        }

        // 退款金额
        $where = [
            ['status', '=', 1],
            ['refund_time', '>=', $date . ' 00:00:00'],
            ['refund_time', '<=', $date . ' 23:59:59']
        ];
        $refundData = Db::name('refund_record')->where($where)->field('link_id, refund_price')->select()->toArray();
        $refund = [];
        foreach ($refundData as $key => $value) {
            $refund[$value['link_id']][] = $value['refund_price'];
        }

        // 统计分销商充值以及分成、手续费
        $distributorResult = array_column($distributor, null, 'id');

        $saveData = [];
        $dateTime = date('Ymd', time() - 86400);
        $month = date('Ym', time() - 86400);

        foreach ($distributorData as $distributorId => $linkId) {
            $rechargePrice = 0;
            $refundPrice = 0;

            foreach ($linkId as $id) {
                $rechargePrice += !empty($rechargeData[$id]) ? array_sum($rechargeData[$id]) : 0;
                $refundPrice += !empty($refund[$id]) ? array_sum($refund[$id]) : 0;
            }

            $commission = round(($rechargePrice - $refundPrice) * 0.3 / 100, 2); //（总充值金额-总退款）*0.3%
            $sharingAmount = round(($rechargePrice - $commission - $refundPrice) * (80 / 100), 2); //（总充值金额-总退款金额-手续费）*80%
            $lySharingAmount = round(($rechargePrice - $commission - $refundPrice) * (20 / 100), 2); //（总充值金额-总退款金额-手续费）*20%

            $saveData[] = [
                'date' => $dateTime,
                'month' => $month,
                'name' => $distributorResult[$distributorId]['name'],
                'distributor_id' => $distributorId,
                'company_name' => Db::name('company')->where('id', $distributorResult[$distributorId]['company_id'])->field('name')->find()['name'],
                'recharge_price' => round($rechargePrice, 2),
                'refund_price' => round($refundPrice, 2),
                'commission' => $commission,
                'scale' => round((80 / 100), 2),
                'sharing_amount' => $sharingAmount,
                'ly_sharing_amount' => $lySharingAmount,
                'created_at' => time(),
            ];
        }

        $bool = Db::name('distributors_h5_sms_sharing_statistics')->insertAll($saveData);
        return $bool;
    }

    // 统计腾讯每天投放数据
    public function tencentDailyDeliveryData()
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);

        // 分销商链接不查询

        $distributorResponsibilityPersonIds = [];

        $distributorResponsibilityPerson = Db::name('responsibility_person')->where(['pid' => Db::raw('IS NOT NULL')])->field(['id', 'pid'])->select()->toArray();

        $distributorResponsibilityPersonPids = array_unique(array_column($distributorResponsibilityPerson, 'pid'));

        $notBranchOfficeManageData = Db::name('responsibility_person')->where([['id', 'in', $distributorResponsibilityPersonPids], ['is_branch_office_manage', '=', 0]])->field(['id'])->select()->toArray();

        $notBranchOfficeManageIds = array_column($notBranchOfficeManageData, 'id');

        foreach ($distributorResponsibilityPerson as $distributorResponsibility) {
            if (in_array($distributorResponsibility['pid'], $notBranchOfficeManageIds)) {
                $distributorResponsibilityPersonIds[] = $distributorResponsibility['id'];
            }
        }
        $date = date('Y-m-d', time() - 86400);

        $linkData = Db::name('link')->where([['media_id', '=', 4], ['link_switch', '=', 1], ['responsibility_person_id', 'not in', $distributorResponsibilityPersonIds]])->field('id, video_id, video_detail_id, advertiser_id, version, project_id, rebate, subject_id, link_type')->select()->toArray();

        if (!empty($distributorResponsibilityPersonIds)) {
            // 获取统计当天关闭投放的链接数据
            $sql = 'select id, video_id, video_detail_id, advertiser_id, version, project_id, rebate, subject_id,link_type from ly_link where media_id=4 and from_unixtime(release_end_time, "%Y%m%d") = ' . date('Ymd', time() - 86400) . ' and responsibility_person_id not in (' . implode(',', $distributorResponsibilityPersonIds) . ')';

            $linkData1 = Db::query($sql);

            $linkAdvertiserIds = array_column($linkData, 'advertiser_id');
            $newlinkData = [];
            foreach ($linkData1 as $key => $value) {
                if (!in_array($value['advertiser_id'], $linkAdvertiserIds)) {
                    $newlinkData[] = $value;
                }
            }
            $linkData = array_merge($linkData, $newlinkData);
        }

        // 获取redis花费数据
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $data = [];

        $developerInfo = config('tencent.developer_info');
        $token = Common::getTencentAdDeveloperAppAccessToken($developerInfo);
        $url = 'https://api.e.qq.com/v1.3/realtime_cost/get';

        foreach ($linkData as $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }
            $commonParameters = [
                'access_token' => $token,
                'timestamp' => time(),
                'nonce' => md5(uniqid('', true))
            ];

            $parameters = [
                'account_id' => $value['advertiser_id'],
                'level' => 'ADVERTISER',
                'date' => $date,
                'page' => 1,
                'page_size' => 10
            ];

            $parameters = array_merge($commonParameters, $parameters);

            foreach ($parameters as $key => $item) {
                if (!is_string($item)) {
                    $parameters[$key] = json_encode($item);
                }
            }

            $requestUrl = $url . '?' . http_build_query($parameters);

            $response = Common::curlRequest($requestUrl);
            $costData = json_decode($response, true);
            // dump($costData);die;
            // 花费
            $value['cost'] = 0;
            if (!empty($costData['data']['list'][0])) {
                $value['cost'] = round($costData['data']['list'][0]['cost'] / 100, 2);
            }

            $data[] = $value;
        }

        if ($data) {
            $ids = array_column($data, 'id');

            $timeStamp = time() - 86400;
            $start = date('Y-m-d', $timeStamp) . ' 00:00:00';
            $end = date('Y-m-d', $timeStamp) . ' 23:59:59';
            $userWhere = [
                ['link_id', 'in', $ids],
                ['activation_time', 'between', [$start, $end]]
            ];
            $userInfo = Db::name('user')->where($userWhere)->field('id, link_id')->select()->toArray();
            $payData = Db::name('pay_record')->where(['link_id' => $ids, 'status' => 1, 'consume_date' => date('Ymd', time() - 86400)])->field('link_id, uid, total_fee, activation_time, pay_merchant')->select()->toArray();

            $activationUids = $newUids = $newUserPayData = $rechargeNumber = $payResult = $activationUserNumData = $registerUserNumData = [];

            if ($userInfo) {
                $activationUids = array_column($userInfo, 'id');

                foreach ($userInfo as $value) {
                    $activationUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            // 注册用户数
            $registerUserData = Db::name('user')->where(['register_date' => date('Ymd', $timeStamp), 'link_id' => $ids])->field('id, link_id')->select()->toArray();
            if ($registerUserData) {
                $newUids = array_column($registerUserData, 'id');
                foreach ($registerUserData as $key => $value) {
                    $registerUserNumData[$value['link_id']][] = $value['id'];
                }
            }

            $newUserNum = $tencentPayData = [];
            // 当天新用户充值（当期充值）
            $endTime = strtotime(date('Y-m-d'));
            $startTime = $endTime - 86400;

            foreach ($payData as $key => $value) {
                if (strtotime($value['activation_time']) >= $startTime && $endTime > strtotime($value['activation_time'])) {
                    $newUserPayData[$value['link_id']][] = $value['total_fee'];
                    $newUserNum[$value['link_id']][] = $value['uid'];
                    if ($value['pay_merchant'] == 15) {
                        $tencentPayData[$value['link_id']][] = $value['total_fee'];
                    }
                }

                $rechargeNumber[$value['link_id']][] = $value['uid'];
            }

            $saveData = [
                'platform' => 4,
                'date' => date('Ymd', time() - 86400),
                'month' => date('Ym', time() - 86400),
                'total_cost' => 0,
                'activation_user_num' => count($activationUids),
                'current_recharge' => 0,
                'current_recovery' => 0,
                'total_recharge' => 0,
                'total_recovery' => 0,
                'fans_cost' => 0,
                'revenue' => 0,
                'per_capita_contribution' => 0,
                'created_at' => time(),
                'register_user_num' => count($newUids),
                'actual_cost' => 0,
                'recharge_user_num' => 0,
                'conversion_rate' => '0%',
                'virtual_payment' => 0,
                'all_cost' => 0,
                'non_grant_cost' => 0,
                'grant_cost' => 0,
                'return_goods_wallet_cost' => 0,
                'balance' => 0,
                'non_grant_balance' => 0,
                'grant_balance' => 0
            ];

            $totalClickNum = 0; // 所有链接总点击数
            $totalNewUserNumber = 0; // 所有链接新充人数

            $todayLanuchData = [];
            foreach ($data as $key => $item) {
                $data[$key]['platform'] = 4;
                $data[$key]['link_id'] = $item['id'];
                $data[$key]['date'] = date('Ymd', time() - 86400);
                $data[$key]['month'] = date('Ym', time() - 86400);

                $currentRecharge = empty($newUserPayData[$item['id']]) ? 0 : array_sum($newUserPayData[$item['id']]);
                if (empty($currentRecharge) && (empty($item['cost']) || $item['cost'] == '0.00')) {
                    continue;
                }
                // 腾讯虚拟支付
                $virtualPayment = empty($tencentPayData[$item['id']]) ? 0 : array_sum($tencentPayData[$item['id']]);
                $saveData['virtual_payment'] += $virtualPayment;
                $data[$key]['virtual_payment'] = $virtualPayment;

                $data[$key]['current_recharge'] = round($currentRecharge, 2); // 当期充值
                $saveData['total_cost'] = $saveData['total_cost'] + $item['cost']; // 总花费
                $saveData['current_recharge'] = $saveData['current_recharge'] + $currentRecharge; // 当天所有链接当期充值

                $conversionNumber = empty($rechargeNumber[$item['id']]) ? 0 : count(array_unique($rechargeNumber[$item['id']])); // 充值人数
                $rechargeSum = empty($rechargeNumber[$item['id']]) ? 0 : count($rechargeNumber[$item['id']]); // 充值笔数
                $data[$key]['conversion_number'] = $conversionNumber;
                $data[$key]['recharge_number'] = $rechargeSum;
                $data[$key]['conversion_cost'] = $conversionNumber == 0 ? 0 : round($item['cost'] / $conversionNumber, 2); // 转化成本
                $saveData['recharge_user_num'] = $saveData['recharge_user_num'] + $conversionNumber;

                $newRechargeNumber = empty($newUserPayData[$item['id']]) ? 0 : count($newUserPayData[$item['id']]); // 新充笔数
                $newUserNumber = empty($newUserNum[$item['id']]) ? 0 : count(array_unique($newUserNum[$item['id']])); // 新充人数
                $data[$key]['new_recharge_number'] = $newRechargeNumber;
                $data[$key]['new_user_number'] = $newUserNumber;
                $totalNewUserNumber = $totalNewUserNumber + $newUserNumber;

                // 激活用户数
                $activationUserNum = !empty($activationUserNumData[$item['id']]) ? count($activationUserNumData[$item['id']]) : 0;
                $data[$key]['activation_user_num'] = $activationUserNum;

                // 转化率
                $data[$key]['conversion_rate'] = empty($activationUserNum) ? '0%' : round($newUserNumber / $activationUserNum * 100, 2) . '%';
                $totalClickNum = $totalClickNum + $activationUserNum;

                $data[$key]['register_user_num'] = !empty($registerUserNumData[$item['id']]) ? count($registerUserNumData[$item['id']]) : 0; // 该链接当日注册用户

                $data[$key]['total_recharge'] = round($currentRecharge, 2);
                $saveData['total_recharge'] = $saveData['total_recharge'] + $currentRecharge; // 总充值

                $data[$key]['per_capita_contribution'] = $newUserNumber == 0 ? 0 : round($currentRecharge / $newUserNumber, 2); // 人均贡献
                $data[$key]['created_at'] = time();

                // 实际花费
                $actualCost = 0;
                if (!empty($item['rebate'])) {
                    $actualCost = round($item['cost'] / ($item['rebate'] / 100 + 1), 2);
                } elseif (!empty($launchAccount[$item['advertiser_id']])) {
                    $actualCost = round($item['cost'] / ($launchAccount[$item['advertiser_id']] / 100 + 1), 2);
                }
                $data[$key]['actual_cost'] = $actualCost;
                $saveData['actual_cost'] = $saveData['actual_cost'] + $actualCost;
                $data[$key]['revenue'] = round($currentRecharge - $actualCost, 2); // 营收情况 = 累计充值 - 实际花费
                $data[$key]['current_recovery'] = $actualCost == 0 ? 0 : round($currentRecharge / $actualCost * 100, 2) . '%'; // 当期回收

                $data[$key]['fans_cost'] = !empty($activationUserNum) ? round($actualCost / $activationUserNum, 2) : 0; // 粉丝成本

                unset($data[$key]['id']);
                unset($data[$key]['video_id']);
                unset($data[$key]['video_detail_id']);
                unset($data[$key]['version']);
                unset($data[$key]['project_id']);
                unset($data[$key]['rebate']);
                unset($data[$key]['subject_id']);

                $todayLanuchData[] = $data[$key];
            }
        }

        // 统计在投所有链接每天的投放数据
        $saveData['current_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['current_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 当期回收
        $saveData['total_recovery'] = !empty($saveData['actual_cost']) ? round($saveData['total_recharge'] / $saveData['actual_cost'] * 100, 2) . '%' : '0.00%'; // 累计回收
        $saveData['fans_cost'] = !empty($saveData['activation_user_num']) ? round($saveData['actual_cost'] / $saveData['activation_user_num'], 2) : 0; // 粉丝成本
        $saveData['revenue'] = round($saveData['total_recharge'] - $saveData['actual_cost'], 2); // 营收情况
        $saveData['per_capita_contribution'] = !empty($saveData['register_user_num']) ? round($saveData['current_recharge'] / $saveData['register_user_num'], 2) : 0; // 人均贡献
        $saveData['total_cost'] = round($saveData['total_cost'], 2);
        $saveData['all_cost'] = round($saveData['all_cost'], 2);
        $saveData['current_recharge'] = round($saveData['current_recharge'], 2);
        $saveData['total_recharge'] = round($saveData['total_recharge'], 2);
        $saveData['conversion_rate'] = !empty($totalClickNum) ? round($totalNewUserNumber / $totalClickNum * 100, 2) . '%' : '0%';

        Db::name('delivery_data')->insert($saveData);

        // 统计在投每条链接每天的投放数据
        $bool = Db::name('daily_delivery_data')->insertAll($todayLanuchData);
        return $bool;
    }

    // 查询以前充值的数据(不包含当天)
    public function basicCooperaterStatistics()
    {
        //查询以前所有的数据
        //查询所有的剧id
        $videoIdData = Db::name('videos')->where(['is_delete' => 0])->field('id')->select()->toArray();
        $videoIds = array_column($videoIdData, 'id');
        //查询最早的充值时间
        $wherePay = [
            ['a.status', '=', 1],
            ['a.video_id', 'in', $videoIds]
        ];
        $videoEarliestData = Db::name('pay_record')->alias('a')->leftjoin('videos t1', 't1.id = a.video_id')->where($wherePay)->field('MIN(a.pay_time) AS earliest_recharge_time,a.video_id,t1.name as video_name')->group('a.video_id')->select()->toArray();
        // var_dump($videoEarliestData);exit;
        //统计数据
        foreach ($videoEarliestData as $k_E => $v_E) {
            $currentDate = date('Y-m-d', time() - 86400);

            // 获取需要统计的起始日期
            $startDate = date("Y-m-d", $videoEarliestData[$k_E]['earliest_recharge_time']); // 统计过去7天的数据，你可以根据需要进行调整

            // 遍历每一天进行统计
            while ($startDate <= $currentDate) {
                // 统计逻辑，根据需要进行具体的数据统计操作
                // 这里只是一个示例，你需要根据实际需求进行相应的统计代码编写
                $saveData = [];
                $dateTime = date('Ymd', $videoEarliestData[$k_E]['earliest_recharge_time']);
                $month = date('Ym', $videoEarliestData[$k_E]['earliest_recharge_time']);

                $date = date('Y-m-d', $videoEarliestData[$k_E]['earliest_recharge_time']);
                $startTime = strtotime($date);
                $endTime = strtotime($date . ' 23:59:59');
                $where = [
                    ['status', '=', 1],
                    ['pay_time', '>=', $startTime],
                    ['pay_time', '<=', $endTime],
                    ['video_id', '=', $videoEarliestData[$k_E]['video_id']]
                ];
                $payData = Db::name('pay_record')->where($where)->field('sum(total_fee) as total_amount')->select()->toArray();
                $rechargeDataAmount = !empty($payData) ? $payData[0]['total_amount'] : 0;
                // var_dump($rechargeDataAmount);exit;


                //自投充值
                $where_per = [
                    ['company_id', 'in', config('enum.self_company_id')]
                ];
                $distributor = Db::name('responsibility_person')->where($where_per)->field('id, name, commission_scale, scale, company_id')->select()->toArray();
                $pitcherIds = array_column($distributor, 'id');

                $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

                $linkIds = array_column($linkData, 'id');

                $whereSelf = [
                    ['status', '=', 1],
                    ['pay_time', '>=', $startTime],
                    ['pay_time', '<=', $endTime],
                    ['link_id', 'in', $linkIds],
                    ['video_id', '=', $videoEarliestData[$k_E]['video_id']]

                ];
                $selfPayData = Db::name('pay_record')->where($whereSelf)->field('sum(total_fee) as total_amount')->select()->toArray();
                $selfDataAmount = !empty($selfPayData) ? $selfPayData[0]['total_amount'] : 0;
                // var_dump($selfDataAmount);exit;
                //写入数据
                $saveData[] = [
                    'date' => $dateTime,
                    'month' => $month,
                    'video_name' => $videoEarliestData[$k_E]['video_name'],
                    'video_id' => $videoEarliestData[$k_E]['video_id'],
                    'total_price' => round($rechargeDataAmount, 2),
                    'self_price' => round($selfDataAmount, 2),
                    'created_at' => time(),
                ];
                $bool = Db::name('daily_cooperater_statistics')->insertAll($saveData);
                // 递增日期
                $startDate = date("Y-m-d", strtotime($startDate . " +1 day"));
            }
            // var_dump($videoEarliestData[$k_E]);exit;
        }
        // var_dump($videoEarliestData);exit;
        echo '最后成功';
    }

    // 合作方每日统计(每天凌晨统计昨天的数据)
    public function dailyCooperaterStatistics()
    {
        $saveData = [];
        $dateTime = date('Ymd', time() - 86400);
        $month = date('Ym', time() - 86400);

        // $videoIdData = Db::name('cooperater')->where(['status' => 1])->field('id, video_id,video_name')->select()->toArray();
        $whereId['is_delete'] = 0;
        // $whereId['is_copy']=0;
        $videoIdData = Db::name('videos')->where($whereId)->field('id as video_id, name as video_name,is_copy,original_id')->select()->toArray();

        $videoIds = array_column($videoIdData, 'video_id');

        $date = date('Y-m-d', time() - 86400);
        $startTime = strtotime($date);
        $endTime = strtotime($date . ' 23:59:59');
        $where = [
            ['status', '=', 1],
            ['pay_time', '>=', $startTime],
            ['pay_time', '<=', $endTime],
            ['video_id', 'in', $videoIds]
        ];
        $payData = Db::name('pay_record')->where($where)->field('video_id, total_fee')->select()->toArray();
        // var_dump($payData);exit;
        $rechargeData = [];
        foreach ($payData as $value) {
            $rechargeData[$value['video_id']][] = $value['total_fee'];
        }

        //自投充值
        $where_per = [
            ['company_id', 'in', config('enum.self_company_id')]
        ];
        $distributor = Db::name('responsibility_person')->where($where_per)->field('id, name, commission_scale, scale, company_id')->select()->toArray();
        $pitcherIds = array_column($distributor, 'id');

        $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

        $linkIds = array_column($linkData, 'id');

        $whereSelf = [
            ['status', '=', 1],
            ['pay_time', '>=', $startTime],
            ['pay_time', '<=', $endTime],
            ['link_id', 'in', $linkIds],
            ['video_id', 'in', $videoIds]
        ];
        $selfPayData = Db::name('pay_record')->where($whereSelf)->field('video_id, total_fee')->select()->toArray();
        // var_dump(Db::name('pay_record')->getlastsql());exit;
        $selfRechargeData = [];
        foreach ($selfPayData as $value1) {
            $selfRechargeData[$value1['video_id']][] = $value1['total_fee'];
        }

        foreach ($videoIdData as $k => $v) {
            $rechargePrice = !empty($rechargeData[$v['video_id']]) ? array_sum($rechargeData[$v['video_id']]) : 0;
            $selfRechargePrice = !empty($selfRechargeData[$v['video_id']]) ? array_sum($selfRechargeData[$v['video_id']]) : 0;

            $saveData[] = [
                'date' => $dateTime,
                'month' => $month,
                'video_name' => $v['video_name'],
                'video_id' => $v['video_id'],
                'total_price' => number_format($rechargePrice, 2),
                'self_price' => number_format($selfRechargePrice, 2),
                'created_at' => time(),
                'is_copy' => $v['is_copy'],
                'original_id' => $v['original_id']
            ];
        }

        //将原始剧和复制剧区分开
        $copyRecharge = [];
        $originalRecharge = [];
        foreach ($saveData as $vS) {
            if ($vS['is_copy'] == 1) { //则是复制剧
                $copyRecharge[] = $vS;
            } else {
                $originalRecharge[] = $vS;
            }
        }
        $mergedRecharge = [];
        foreach ($originalRecharge as $original) {
            $mergedRecharge[$original['video_id']] = [
                'date' => $dateTime,
                'month' => $month,
                'video_name' => $original['video_name'],
                'video_id' => $original['video_id'],
                'total_price' => $original['total_price'],
                'self_price' => $original['self_price'],
                'created_at' => time(),
            ];
        }

        foreach ($copyRecharge as $copy) {
            if (isset($mergedRecharge[$copy['original_id']])) {
                $mergedRecharge[$copy['original_id']]['total_price'] += $copy['total_price'];
                $mergedRecharge[$copy['original_id']]['self_price'] += $copy['self_price'];
            }
            $mergedRecharge[$copy['original_id']]['total_price'] = number_format($mergedRecharge[$copy['original_id']]['total_price'], 2);
            $mergedRecharge[$copy['original_id']]['self_price'] = number_format($mergedRecharge[$copy['original_id']]['self_price'], 2);
        }

        $bool = Db::name('daily_cooperater_statistics')->insertAll($mergedRecharge);
        return $bool;
    }

    public function videoStatisticPlan()
    {
        $redis = Cache::store('redis')->handler();
        $videoKey = config('redis_key.video_statistic_count_key');
        $redis->select(2);
        $videoInfo = $redis->hGetAll($videoKey) ?: [];
        if (empty($videoInfo)) return json(['msg' => 'no cache']);
        //删除短剧hash
        $redis->del($videoKey);

        $list = Db::name('videos')->field('id,total_consume,give_count,frequency,number')
            ->where(['is_delete' => 0])->select()->toArray();

        $time = time();
        $detailModel = new VideoDetails();
        $videoModel = new Videos();
        foreach ($list as $item) {
            $video_id = $item['id'];
            $videoDetailKey = config('redis_key.video_detail_statistic_count_key') . $video_id;
            $redis->select(2);
            $detailInfo = $redis->hGetAll($videoDetailKey) ?: [];
            if (!empty($detailInfo)) {
                //删除该hash
                $redis->del($videoDetailKey);
                $details = Db::name('video_details')->field('id,give_count,today_number,number,frequency')
                    ->where(['video_id' => $video_id, 'is_delete' => 0])->select()->toArray();

                $bigDetailData = [];
                foreach ($details as $detail) {
                    $video_detail_id = $detail['id'];
                    $detailData = [];
                    if (isset($detailInfo['frequency_' . $video_detail_id])) {
                        $detailData['frequency'] = $detail['frequency'] + $detailInfo['frequency_' . $video_detail_id];
                    }

                    if (isset($detailInfo['number_' . $video_detail_id])) {
                        $detailData['number'] = $detail['number'] + $detailInfo['number_' . $video_detail_id];
                    }

                    if (isset($detailInfo['give_count_' . $video_detail_id])) {
                        $detailData['give_count'] = $detail['give_count'] + $detailInfo['give_count_' . $video_detail_id];
                        $detailData['give_count'] = $detailData['give_count'] > 0 ? $detailData['give_count'] : 0;
                    }

                    if (!empty($detailData)) {
                        $detailData['id'] = $video_detail_id;
                        $detailData['updated_at'] = $time;
                        $bigDetailData[] = $detailData;
                    }
                }

                if ($bigDetailData) $detailModel->saveAll($bigDetailData);
            }

            $videoData = [];
            if (isset($videoInfo['frequency_' . $video_id])) {
                $videoData['frequency'] = $item['frequency'] + $videoInfo['frequency_' . $video_id];
            }

            if (isset($videoInfo['give_count_' . $video_id])) {
                $videoData['give_count'] = $item['give_count'] + $videoInfo['give_count_' . $video_id];
            }

            if (isset($videoInfo['number_' . $video_id])) {
                $videoData['number'] = $item['number'] + $videoInfo['number_' . $video_id];
            }

            if (isset($videoInfo['total_consume_' . $video_id])) {
                $videoData['total_consume'] = round($item['total_consume'] + $videoInfo['total_consume_' . $video_id]);
            }

            if ($videoData) {
                $videoData['updated_at'] = $time;
                $videoModel->update($videoData, ['id' => $video_id]);
            }
        }
        return json(['msg' => 'success']);
    }
    // 生成广告金列表列表(每周一生成上一周广告金数据，所选时间T-3)
    public function generateAdFundsListNew()
    {
        $params = Request::param();
        $startDate = $params['startDate'];
        $endDate = $params['endDate'];
        $where = [
            ['a.consume_date', '>=', $startDate],
            ['a.consume_date', '<=', $endDate],
            ['a.pay_merchant', '=', 15],
            ['a.status', '=', 1],
            ['a.link_id', '>=', 1],
            ['t2.id', '=',  $params['applet_id']],
        ];
        $payRecordData = Db::name('pay_record')->alias('a')->leftjoin('link b', 'a.link_id = b.id')->leftjoin('responsibility_person c', 'b.responsibility_person_id = c.id')->leftjoin('company d', 'c.company_id = d.id')->leftjoin('user t1', 'a.uid = t1.id')->leftjoin('applet t2', 't1.applet_id = t2.id')->leftjoin('refund_record t3', 'a.order_no = t3.order_no')->where($where)->field('d.id as company_id,d.name as company_name, t2.id as applet_id ,t2.name as applet_name,a.total_fee as price,a.order_no,t3.refund_price')->group('a.order_no')->order('t3.status asc')->select()->toArray();

        //根据对应的条件进行组装

        $settlementData = $appletIds = [];
        foreach ($payRecordData as $key => $value) {
            if ($value['order_no'] == '202312020114124375') {
                continue;
            }
            $settlementData[$value['applet_id']][] = $value;
            $appletIds[] = $value['applet_id'];
            $companyIds[] = $value['company_id'];
        }

        $settlementData2 = $settlementData3 = $appletIds2 = [];
        foreach ($settlementData as $keyD2 => $valueD2) {
            $settlementData3 = [];
            foreach ($valueD2 as $keyD3 => $valueD3) {
                if ($valueD3['applet_id'] == $keyD2) {
                    $settlementData3[$valueD3['company_id']][] = $valueD3;
                }
            }
            if (!empty($settlementData3)) {
                $settlementData2[$keyD2] = $settlementData3;
            }
        }

        //统计金额和退款。并结算广告金（腾讯广告金：结算周期T-3内的(订单充值金额-退款)*5% ）
        $saveData = [];
        foreach ($settlementData2 as $key1 => $value1) {
            $settlementPrice = 0;
            $settlementRefundPrice = 0;
            foreach ($value1 as $item1) {

                $settlementPrice = array_sum(array_column($item1, 'price'));
                $settlementRefundPrice = array_sum(array_column($item1, 'refund_price'));
                if (!empty($settlementPrice) && $settlementPrice > 0) {
                    $tx_ad_price = ($settlementPrice - $settlementRefundPrice) * 0.05;
                    //    var_dump($tx_ad_price);
                    $saveData[] = [
                        'company_id' => $item1[0]['company_id'],
                        'company_name' => $item1[0]['company_name'],
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                        'price' => round($settlementPrice, 2),
                        'refund_price' => round($settlementRefundPrice, 2),
                        'tx_ad_price' => round($tx_ad_price, 2),
                        'applet_id' => $item1[0]['applet_id'],
                        'applet_name' => $item1[0]['applet_name']
                    ];
                }
            }
        }
        //    var_dump($saveData);die;
        foreach ($saveData as $key => $val) {
            $find = Db::name('ad_funds')->where(['applet_id' => $val['applet_id'], 'company_id' => $val['company_id'], 'start_date' => $val['start_date'], 'end_date' => $val['end_date']])->find();
            if (!empty($find)) {
                Db::name('ad_funds')->where(['id' => $find['id']])->update($val);
            }
        }
        return Common::success($saveData);
    }
}
